1

I've come across a problem with using Regular Expressions in Java. I'm trying to replace everything in a string that doesn't match my expression. Example:

String string = "This is test string (1) of 10";

Basically, I need to remove all the characters in the string to get the value inside the brackets to change it later on. I though that the following would work:

string.replaceAll("^[\\([0-9]\\)]", "(" + nextNumber  +")" );

However, it doesn't. I have also tried:

string.replaceAll("(?!\\([0-9]\\)])", "(" + nextNumber  +")" );

Does anyone know of a better way of getting the value inside the brackets, or could you tell me how I can replace all the characters in the string except the value inside the brackets?

1 Answer 1

3

You can try

string.replaceAll("\\([0-9]\\)", "(" + nextNumber  +")" );

There is no need of ^ that represents start of the line.

If the number is more than one digit then try \\([0-9]+\\) and you can use \\d instead of [0-9]

For more info have a look at Java Regex Pattern

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

Comments

Your Answer

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