Regex to find String with square bracket and replace

Suren

New Member
#1
My current Code is
Mã:
`
String text= "[School_Teacher_Name] is our new member, So please congratulate [School_Teacher_Name] .";
String tag = "[School_Teacher_Name]";
String value= "Yash Mathur";
String str1 = tag.substring(1, tag.length()-1);
String reg = "/\\["+str1+"\\]/";

if(text.contains(tag)){
   return text.replaceAll(reg, value).trim();
}
else{
   return text;
}`
I dont have much experience in regex. my code is not replacing any value, Please help me out.
 

Admin

Administrator
Thành viên BQT
#2
If I don't misunderstood you requirements then you can do this way. Regex

Java

Mã:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "\\[(School_Teacher_Name)]";
final String string = "[School_Teacher_Name] is our new member, So please congratulate [School_Teacher_Name] .";
final String subst = "Yash Mathur";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);
Javascript
Mã:
const regex = /\[(School_Teacher_Name)]/gm;
const str = `[School_Teacher_Name] is our new member, So please congratulate [School_Teacher_Name] .`;
const subst = `Yash Mathur`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);
 
Top