What is the Regular Expression to find the strings starting with [ and ending with ]. Between [ and] all kind of character are fine.
To match the start or the end of a line, we use the following anchors: Caret (^) matches the position before the first character in the string. Dollar ($) matches the position right after the last character in the string.
Explanation: '^' (carat) matches the start of the string. '$' (dollar sign) matches the end of the string. Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.
End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.
As usual, the regex engine starts at the first character: 7. The first token in the regular expression is ^. Since this token is a zero-length token, the engine does not try to match it with the character, but rather with the position before the character that the regex engine has reached so far.
[
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
.
^\[.*\]$
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With