简要介绍C#中正则表达式Regex的match和matches方法

来源:百度知道 编辑:UC知道 时间:2024/05/30 10:06:01
如题,谁有经验的讲讲,在vs里标明它们分别返回match和matchcollection类型,不懂呢?一般怎么用?
比方说,我定义一个字符串string s="aaaa(bbb)aaaaaaaaa(bb)aaaaaa" ,写一个正则表达式来匹配括号中的内容:\(/w+\)
就可以用match方法得到匹配字符串result="(bbb)"或者"(bb)"
用matches方法得到字符串组result[2]={"(bbb)","(bb)"}
是这样吗?是的话代码怎么写呢?
解决了我再加50分

你的理解没错。你可以用以下程序验证:
string s = "aaaa(bbb)aaaaaaaaa(bb)aaaaaa";
string pattern = "\\(\\w+\\)";
Match result = Regex.Match(s,pattern);
MatchCollection results = Regex.Matches(s,pattern);
然后你会看到
result.Value = {(bbb)};
results[0].Value = {(bbb)};
results[1].Value = {(bb)};
也就是match会捕获第一个匹配。而matches会捕获所有的匹配。
——————————————————
matchcollection result = Regex.matches(s)
match类型就是一个单独的捕获,matchcollection就是一组捕获。