RegEx Starts with [ and ending with ]

前端 未结 4 1799
广开言路
广开言路 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 ]
    
    0 讨论(0)
  • 2020-12-10 03:13

    [ and ] are special characters in regular expressions, so you need to escape them. This should work for you:

    \[.*?\]
    

    .*? does non-greedy matching of any character. The non-greedy aspect assures that you will match [abc] instead of [abc]def]. Add a leading ^ and trailing $ if you want to match the entire string, e.g. no match at all in abc[def]ghi.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-10 03:15

    You need to use escape character \ for brackets.
    Use .+ if you like to have at least 1 character between the brackets or .* if you accept this string: [].

    ^\[.*\]$
    
    0 讨论(0)
提交回复
热议问题