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,446
  • 8
  • 30
  • 57
Pecana
  • 323
  • 4
  • 17

2 Answers2

5

Use a negative lookbehind:

name = name.replaceAll("(?<!\\+)1", "one");
YCF_L
  • 51,266
  • 13
  • 85
  • 129
Toto
  • 86,179
  • 61
  • 85
  • 118
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
  • 29,014
  • 15
  • 50
  • 74