0

in java i need to replace a number with a word only if it is not preceeded by the "+". Example:

- match1
- match+1

Should become:

matchone
match+1 (no modify)

I tried with

>>>name = name.replaceAll("([^+])1", "one");
matcone                                      //required "matchone"

But it is not working. Any suggestions?

Thank you

Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
Pecana
  • 363
  • 5
  • 17

2 Answers2

6

Use a negative lookbehind:

name = name.replaceAll("(?<!\\+)1", "one");
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Toto
  • 89,455
  • 62
  • 89
  • 125
1

Your regex is eating the character before the one and replacing that with "one" as well, so the output in the first instance is "matcone".

You can use a negative look-behind expression (?<!) to match any "1" that is not preceded by a "+":

name = name.replaceAll("(?<!\\+)1", "one");
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79