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:
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)]"
CodePudding user response:
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)]