简体   繁体   中英

Regex to find String with square bracket and replace

my current Code is

`
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.

Remove forward slashes from your regex.

Change

String reg = "/\\["+str1+"\\]/";

to

String reg = "\\["+str1+"\\]";

Output

Yash Mathur is our new member, So please congratulate Yash Mathur .

PS - In this case it's better to use text.replace(tag, value) instead of text.replaceAll(reg, value)

If I don't misunderstood you requirements then you can do this way. Regex

Java

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

 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); 

It's far easier with Template Literals .

 let teacher = 'Yash Mathur'; let test = `${teacher} is our new member, so please congratulate ${teacher}.`; console.log(test); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM