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

Time:10-20

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 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.

https://regexr.com/67qk7

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

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

Screenshot from Regex101

  • Related