Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java – non greedy-regex to replace partial string in longer words?

I have a string like that:

  $c+350 - $c + $c_new * $c_new[x(12345)]

Here, I only want to replace the first two $c (as they don’t have any followed characters [A-Za-z0-9_]) with $text

I tried to use with Java regex pattern:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

String a = "$c+350 - $c + $c_new * $c_new[x(12345)]";
String b = a.replaceAll("\\$c[^A-Za-z0-9_]",  "\\$text")

but it only returns with one stripped character for each $text

b = "$text350 - $text+ $c_new * $c_new[x(12345)]"

instead of the text it should be:

b = "$text+350 - $text + $c_new * $c_new[x(12345)]"

>Solution :

You should be able to find \$c\b and replace with $text:

String input = "$c+350 - $c + $c_new * $c_new[x(12345)]";
String output = input.replaceAll("\\$c\\b", "\\$text");
System.out.println(output);

This prints:

$text+350 - $text + $c_new * $c_new[x(12345)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading