0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thankyou so much for the detailed explanation. You made it quite clear for me :-)
Hi @Wiktoe I have a doubt what is m.group(1) used for?
@Hannah m.group(1) is a method of m Matcher object that gets the string value of the first capturing group in the regular expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.