wyc
wyc

Reputation: 55293

Match a line with a [ character, but don't match if it has a ] character

I thought this regex would match lines with a [, but not if it has a ]:

^.*\[.*(?!\]).*$

Instead, it's matching every line with a [ (shown in bold):

This [should match]. This line should match

This line shouldn't match.

This line shouldn't match. This line [shouldn't match.

How to fix that regex so that it doesn't match lines that have a ]?

This [should match]. This line should match

This line shouldn't match.

This line shouldn't match. This line [shouldn't match.

Demo: https://regexr.com/67qk7

Upvotes: 3

Views: 107

Answers (3)

JGomez
JGomez

Reputation: 139

"This regex would match lines with a [" (one or more), "but not if it has a ]" (one or more):

^[^\][\n]*\[[^\]\n]*$

Screenshot from Regex101

Upvotes: 1

anubhava
anubhava

Reputation: 785541

An alternate solution which is not super efficient but is a bit shorter:

^(?!.*\[[^\]\n]*$)[^[\n]*\[.+$

RegEx Demo

Explanation:

  • (?!.*\[[^\]\n]*$) fails the match if we get a [ without a closing ] anywhere
  • [^[\n]*\[ matches first [ in a line

Upvotes: 4

The fourth bird
The fourth bird

Reputation: 163457

This pattern ^.*\[.*(?!\]).*$ matches [ and the directly following .* will match the rest of the line.

Then at the end of the line it will assert not ] directly to the right, which is true because it already is at the end of the line. Then the .* is optional and it can assert the end of the string.

So it will match any whole line that has at least a single [

If you want to match pairs of opening till closing square brackets [...] and not allow any brackets inside it, or single brackets outside of it and matching at least a single pair, you can repeat 1 or more times matching pairs surrounded by optional chars other than square brackets.

^(?:[^\][\n]*\[[^\][\n]*\])+[^\][\n]*$

Regex demo

Upvotes: 4

Related Questions