简体   繁体   中英

Using regex for doing string operation

I have a string

String s="my name is ${name}. My roll no is  ${rollno} "

I want to do string operations to update the name and rollno using a method.

public void name(String name, String roll)
{
String new = s.replace(" ${name}", name).replace(" ${rollno}", roll);


}

Can we achieve the same using some other means like using regex to change after first "$" and similarly for the other?

You can use either Matcher#appendReplacement or Matcher#replaceAll (with Java 9+):

A more generic version:

String s="my name is ${name}. My roll no is ${rollno} ";
Matcher m = Pattern.compile("\\$\\{([^{}]+)\\}").matcher(s);
Map<String,String> replacements = new HashMap();
replacements.put("name","John");
replacements.put("rollno","123");
StringBuffer replacedLine = new StringBuffer();
while (m.find()) {
if (replacements.get(m.group(1)) != null)
    m.appendReplacement(replacedLine, replacements.get(m.group(1)));
else
    m.appendReplacement(replacedLine, m.group());
}
m.appendTail(replacedLine);
System.out.println(replacedLine.toString());
// => my name is John. My roll no is 123 

Java 9+ solution:

Matcher m2 = Pattern.compile("\\$\\{([^{}]+)\\}").matcher(s);
String result = m2.replaceAll(x -> 
    replacements.get(x.group(1)) != null ? replacements.get(x.group(1)) : x.group());
System.out.println( result );
// => my name is John. My roll no is 123

See the Java demo .

The regex is \\$\\{([^{}]+)\\} :

  • \\$\\{ - a ${ char sequence
  • ([^{}]+) - Group 1 ( m.group(1) ): any one or more chars other than { and }
  • \\} - a } char.

See the regex demo .

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