Reputation: 511
So if I have these lines:
test 1
[test 2]
[test] 3
test [4]
[test][5]
[te]st[6]
I would like only the 2nd and 5th lines to be matched ([test 2]
, [test][5]
).
I know that we can match what's inside a pair of square brackets with regex
\[.*?\]
But how do we deal with multiple pairs and how to tell it to not match the line if there's anything outside of the square brackets?
Thanks
Upvotes: 0
Views: 893
Reputation: 1
i know its too late, but you can try this one.
/([[][a-zA-Z0-9]*])/gi
all text outside square brackets will be unmatch. im just solved my problem same as on your post.
Upvotes: 0
Reputation: 626748
You can use
^(?:\[[^][]*])+$
^(?:\[[^\]\[]*\])+$
See the regex demo. Details:
^
- start of string(?:
- start of a non-capturing group (remove ?:
if you do not care or if non-capturing groups are not supported):
\[
- a [
char[^][]*
- zero or more chars other than ]
and [
]
- a ]
char)+
- one or more repetitions of the pattern sequence inside the group$
- end of string.NOTE: in some regex flavors you need to escape more [
/ ]
than in others, so to play safe, I added the fully escaped regex version.
Upvotes: 1