-2

hi i want to use Java string replaceAll() method to replace "x3" with "multiplied by 3" in my text file. But there is a string occurence "xxx3" which i do not want to replace. how can I do it

Example :

        ACTUAL                                     DESIRED  
1)ENGAGE XX3 COLOGNE 165ML          ENGAGE XX3 COLOGNE 165ML
2)FDW MEN REFRESHING PULSE 125GMSX3   FDW MEN REFRESHING PULSE 125GMS multuiplied by 3
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
sujit
  • 455
  • 6
  • 12

1 Answers1

4

Try

StringName.replaceAll("(?<!x)x3", "multiplied by 3");

replaceAll method uses a regex as first argument, this pattern has two parts :

"x3" : each time the method finds "x3" in your string, there is a chance to match the pattern

"(?<!x)" is a negative lookbehind. That means : "If my current part of the string is precedeed by x, the pattern will not match, else it will"

e.g. : "(?<!example)x3" will match each "x3" in your string, except any "examplex3"

Hope it helped you

Charly
  • 282
  • 1
  • 12