简体   繁体   中英

C# Regular expression pattern what this matches for

能有人解释这个正则表达式将检查什么

Regex x = new Regex("{([^}]+)}");

It looks for a {...} with some (1 or more) non-} inside. If successful it puts the content of the {...} in capture group 1.

Regex x = new Regex("{([^}]+)}");
var m = x.Match("{Hello}");

string str0 = m.Groups[0].ToString(); // {Hello}
string str1 = m.Groups[1].ToString(); // Hello

Group 0 is always the whole match.

var m2 = x.Match("{}");
var success = m2.Success; // false

It isn't anchored, so it could have more than one match for each string...

var m2 = x.Matches("{Hello}{}{World}");
int c = m2.Count; // 2 matches. The {} wasn't a match, {Hello} and {World} were

As a sidenote, if you think this is the beginning for a good C# parser, you are on the wrong road :-) Expressions like { { string str = "Hello"; } str += "x"; } { { string str = "Hello"; } str += "x"; } { { string str = "Hello"; } str += "x"; } will confuse this regex, so expressions like { string str = "}" } . This is a stackless regex. No fancy tricks.

It matches anything between curly braces, if there at least one character.

There is group () inside braces {} . This group should have at least one []+ symbol which is not closing brace ^} .

它匹配花括号之间的任何内容,例如{ddhhh13233dddd} {ddd}

This will catch everything within the curly brackets.

This MSDN article can explain it in more detail.

This will catch everything within the curly brackets.

I find this tool is the best for explaining Regex's

http://tinyurl.com/lz3d458

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM