3

in java regex,use [^x] to matching "not" with one char.

i want to know,how to matching more chars not?

i using [^789],it's not right.

    String text="aa(123)bb(456)cc(789)dd(78)";
    text=text.replaceAll("\\([^789].*?\\)","");

    System.out.println(text);

i want get result is:

aabbcc(789)dd

how to fix my regex pattern?

thanks a lot :)

0

1 Answer 1

7

You can use a negative lookahead:

"\\((?!789\\)).*?\\)"

Explanation:

\\(     Match a literal open parenthesis "("
(?!     Start negative lookahead
789\\)  Match literal "789)"
)       End lookahead
.*?     Match any characters (non-greedy)
\\)     Match a literal close parenthesis ")"

If the pattern inside the negative lookahead matches then negative lookahead fails to match.

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.