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

后端 未结 2 1648
醉梦人生
醉梦人生 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]+.

    0 讨论(0)
  • 2021-01-28 10:33

    I have changed your regex (actually simpler) to do what you want:

    \[A\].*\[?\[\]\]?
    

    It starts by matching the '[A]', then matches any number of any characters (greedy) and finally one or two '[]'.

    Edit:

    This will prefer double Square brackets:

    \[A\].*(?:\[\[\]\]|\[\])
    
    0 讨论(0)
提交回复
热议问题