What is the Regular Expression to find the strings starting with [ and ending with ]. Between [ and] all kind of character are fine.
[
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, eg 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 (eg 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 ]
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);
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: []
.
^\[.*\]$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.