How to tell a RegEx to be greedy on an 'Or' Expression

后端 未结 2 1647
醉梦人生
醉梦人生 2021-01-28 09:36

Text:

[A]I\'m an example text [] But I want to be included [[]]
[A]I\'m another text without a second part []

Regex:

\\[A\\][\\         


        
2条回答
  •  伪装坚强ぢ
    2021-01-28 10:32

    You may use

    \[A][\s\S]*?(?=\[A]|$)
    

    See the regex demo.

    Details

    • \[A] - a [A] substring
    • [\s\S]*? - any 0+ chars as few as possible
    • (?=\[A]|$) - a location that is immediately followed with [A] or end of string.

    In C#, you actually may even use a split operation:

    Regex.Split(s, @"(?!^)(?=\[A])")
    

    See this .NET regex demo. The (?!^)(?=\[A]) regex matches a location in a string that is not at the start and that is immediately followed with [A].

    If instead of A there can be any letter, replaces A with [A-Z] or [A-Z]+.

提交回复
热议问题