RegEx Starts with [ and ending with ]

前端 未结 4 1807
广开言路
广开言路 2020-12-10 02:43

What is the Regular Expression to find the strings starting with [ and ending with ]. Between [ and] all kind of character are fine.

4条回答
  •  臣服心动
    2020-12-10 03:15

    This should work:

    ^\[.+\]$
    

    ^ is 'start of string'
    \[ is an escaped [, because [ is a control character
    .+ matches all strings of length >= 1 (. is 'any character', + means 'match previous pattern one or more times')
    \] is an escaped ]
    $ is 'end of string'

    If you want to match [] as well, change the + to a * ('match zero or more times')

    Then use the Regex class to match:

    bool match = Regex.IsMatch(input, "^\[.+\]$");
    

    or, if you're using this several times or in a loop, create a Regex instance for better performance:

    private static readonly Regex s_MyRegexPatternThingy = new Regex("^\[.+\]$");
    
    bool match = s_MyRegexPatternThingy.IsMatch(input);
    

提交回复
热议问题