views:

583

answers:

1

I have a string that looks like this: "mynum(1234) and mynum( 123) and mynum ( 12345 ) and lastly mynum(#123)"

I want to insert a "#" in front of the numbers in parenthesis so I have: "mynum(#1234) and mynum( #123) and mynum ( #12345 ) and lastly mynum(#123)"

How can I do this? Using regex pattern matcher and a replaceAll chokes on the "(" in front of the number and I get an "java.util.regex.PatternSyntaxException: Unclosed group near ..." exception.

+3  A: 

Try:

String text = "mynum(1234) and mynum( 123) and foo(123) mynum ( 12345 ) and lastly mynum(#123)";
System.out.println(text.replaceAll("mynum\\s*\\((?!\\s*#)", "$0#"));

A small explanation:

Replace every pattern:

mynum   // match 'mynum'
\s*     // match zero or more white space characters
\(      // match a '('
(?!     // start negative look ahead
  \s*   //   match zero or more white space characters
  #     //   match a '#'
)       // stop negative look ahead

with the sub-string:

$0#

Where $0 holds the text that is matched by the entire regex.

Bart Kiers
+1: more complete response than mine
Rubens Farias
Thank you. I forgot also forgot one other important part to my question...The replace part needs to also account for the mynum word being included in the string.For example, if I had this string:"mynum (1234) and mynum( 123) and ( 12345 ) and mynum(#123)"It would need to look like this:"mynum (#1234) and mynum( #123) and ( 12345 ) and mynum(#123)" where only the numbers in parens after the word mynum (with 0 or more spaces between mynum and the open paren) would be replaced, but we don't bother with any numbers in parens that don't follow the word mynum.
KT
@KT: See the edit.
Bart Kiers
Awesome!!! That worked. Also, thank you for the explanation. That was very helpful.Now I just need to do some research to understand what is "negative look ahead"
KT
@KT: have a look at this tutorial: http://www.regular-expressions.info/lookaround.html
Bart Kiers