3

I'm trying to find a substring that contains a "]" without a "|" in front of it. How can I possibly do this with regex?

0

3 Answers 3

4

/(?<!\|)\]/ is the regex you need.

?<! is a zero-width assertion also known as "negative lookbehind." This essentially means match ], but "look behind" and assert that the previous character isn't a |

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

5 Comments

@NullUserExceptionఠ_ఠ don't you need to double escape | and ] ?
@FailedDev Yes, but this is not my answer. I just added an explanation on what ?<! is.
Just FYI, the leading and trailing slashes are not part of the regex. Many people include them for traditional reasons, but I think that causes unnecessary confusion. The regex is (?<!\|)\]; if you were using it in Perl you would probably write it as /(?<!\|)\]/, but in Java source code it should look like this: "(?<!\\|)\\]".
Thank you NullUserException for the added clarification - I was going to clarify but couldn't do so in a way that satisfied me >_>. And thank you Alan Moore for the further clarification.
2
/(?<!\|)\]/

Use negative lookbehind.

For java :

Pattern regex = Pattern.compile("(?<!\\|)\\[");

Comments

1

Very simply: [^|]\].

If you also want to match a [ at the beginning of a string, use (^|[^|])\]

1 Comment

Won't match the string "]".

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.