Regular expression to get text between square brackets including disparity?

后端 未结 4 417
心在旅途
心在旅途 2021-01-29 12:31

I need to find a regular expression for use in C# (JavaScript as well), for get the text inside the either square brackets combination.

I try several ways, but I give up

相关标签:
4条回答
  • 2021-01-29 12:43

    If you prefer to use a regular expression, the following will work.

    \[([^[\]]+)\]
    

    See Live Demo

    Consider replacing those characters instead of trying to match between them.

    String input  = @"[[[text]]]]]]]]]]]]]";
    String output = Regex.Replace(input, @"[[\]]", "");
    Console.WriteLine(output); //=> "text"
    
    0 讨论(0)
  • 2021-01-29 12:44

    This will exclude the square brackets:

    ((?!\[)(?!\]).)+
    

    Demo

    Explanation

    0 讨论(0)
  • 2021-01-29 12:50

    This matches everything except square brackets: [^\[\]]+

    This captures anything that is not a square bracket between any number of open (LHS) and close (RHS) square brackets:

    \[+([^\[\]]+)\]+

    Example usage in Javascript:

    '[[[[[test]]]]'.match(/\[+([^\[\]]+)\]+/)
    > ["[[[[[test]]]]", "test"]
    

    The regex tester at http://regexpal.com/ is useful for trying out regexes.

    0 讨论(0)
  • 2021-01-29 13:05

    Try this

    This matches everything except square brackets:

    \[([^\[\]]+)\]

    Output

    text

    text

    tex

    0 讨论(0)
提交回复
热议问题