RegEx Starts with [ and ending with ]

前端 未结 4 1811
广开言路
广开言路 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:04

    ^\[.*\]$
    

    will match a string that starts with [ and ends with ]. In C#:

    foundMatch = Regex.IsMatch(subjectString, @"^\[.*\]$");
    

    If you're looking for bracket-delimited strings inside longer strings (e. g. find [bar] within foo [bar] baz), then use

    \[[^[\]]*\]
    

    In C#:

    MatchCollection allMatchResults = null;
    Regex regexObj = new Regex(@"\[[^[\]]*\]");
    allMatchResults = regexObj.Matches(subjectString);
    

    Explanation:

    \[        # match a literal [
     [^[\]]*  # match zero or more characters except [ or ]
    \]        # match a literal ]
    

提交回复
热议问题