Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching a character, but not when it's enclosed in square bracket

Tags:

c#

.net

regex

Input string:

[Wsg-Fs]-A-A-A-Cgbs-Sg7-[Wwg+s-Fs]-A-A-Afk-Cgbs-Sg7

Desired output is a string array:

[Wsg-Fs] A A A Cgbs Sg7 [Wwg+s-Fs] A A Afk Cgbs Sg7

If I split the input string with - as delimiter, the string within square brackets also gets split.

How do I split the string such that - within square bracket should be ignored?

I could find some similar posts trying to ignore delimiter enclosed in quotes, however I have not been able to apply those solution to my problem.

Any suggestion would be really helpful. Thanks!

like image 301
Aqua267 Avatar asked Dec 21 '22 16:12

Aqua267


1 Answers

Assuming there are no nested square brackets, you can use the following to only match - characters that are outside of square brackets:

-(?![^\[]*\])

Example: http://regex101.com/r/sX5hZ2

This uses a negative lookahead, with the logic that if there is a closing square bracket before any opening square brackets, then the - that we tried to match is inside of brackets.

like image 179
Andrew Clark Avatar answered Dec 30 '22 09:12

Andrew Clark