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

前端 未结 2 1526
别那么骄傲
别那么骄傲 2020-11-29 11:37

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         


        
2条回答
  •  醉酒成梦
    2020-11-29 12:15

    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.

提交回复
热议问题