开发者

RegEx Starts with [ and ending with ]

What is the Regular Expression to find the strings starting with [ and ending with ]. Be开发者_Python百科tween [ 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, 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 ]


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: [].

^\[.*\]$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜