Reputation: 55293
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
Reputation: 139
"This regex would match lines with a [" (one or more), "but not if it has a ]" (one or more):
^[^\][\n]*\[[^\]\n]*$
Upvotes: 1
Reputation: 785541
An alternate solution which is not super efficient but is a bit shorter:
^(?!.*\[[^\]\n]*$)[^[\n]*\[.+$
Explanation:
(?!.*\[[^\]\n]*$)
fails the match if we get a [
without a closing ]
anywhere[^[\n]*\[
matches first [
in a lineUpvotes: 4
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]*$
Upvotes: 4