Search code examples
javaregexreplaceall

using java regex how can I replace all when pattern contains left parenthesis


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.


Solution

  • 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.