0

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.

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: have a look at this tutorial: regular-expressions.info/lookaround.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.