2

I am needing a bit of assistance in a regular expression I am trying to create, I am usually pretty good with these but this one has me stuck...

I am needing to replace the number 9 in strings on the fly with \d (creating a new regular expression). These are some example strings that can be expected:

X(29)

9(5)

99

X(29)V999S

Now before you answer too quickly, we must not touch the numbers in the brackets... I have looked at a couple of other answers on here and there is probably something in this solution, but I cannot seem to adapt it - Regex for splitting a string using space when not surrounded by single or double quotes

So far I have come up with

line.replaceAll("[^(\\d)]??9[^)]??", "\\d");

which gives me

X(2\d)

\d(5)

\d\d

X(2\d)V\d\d\dS

Anyone have any thoughts.

Community
  • 1
  • 1
Tony White
  • 143
  • 4
  • I believe I have worked it out! line.replaceAll("9(?![\\d]*\\))", "\\d") Basically it says the 9 is replaceable as long as it does not have a closing bracket after it... it accounts for 9(999), which I bet will turn up at some point. – Tony White Apr 20 '12 at 02:34

2 Answers2

2

given that your rules are pretty straight-forward but just difficult to implement with regular expressions, why not do-it-yourself? Iterate over the string and create a new string keeping track of the state (in brackets or out).

Barry

barry
  • 201
  • 1
  • 4
  • +1 for this suggestion. The regular expression given by Michael probably works, but it's not **obvious** how it works. A simple loop would be clear and easy to understand. – Li-aung Yip Apr 20 '12 at 02:33
2

What about this?

(?!\([^\(]*)9(?![^\(]*\))
Michael Frederick
  • 16,664
  • 3
  • 43
  • 58
  • I cannot post my answer for 8hrs, so until then your answer will suffice for anyone looking for similar, and alternative is line.replaceAll("9(?![\\d]*\))", "\\d") – Tony White Apr 20 '12 at 02:47