C# 正则表达式问题

来源:百度知道 编辑:UC知道 时间:2024/05/18 04:53:58
我遇到一个问题,请高手帮忙看一下
Regex r = new Regex("o");
Match m = r.Match("HelloWorld!");

if (m.Success)
{
Response.Write("搜索成功!");
Response.Write("位置" + m.Index);
}
else
{
Response.Write("没有搜索成功!");
}

执行结果: 搜索成功!位置4

好像程序从不搜索World!这个单词是的,老是搜索前面的Hello 这是为什么?
原来是这样啊!还有一个引申的问题,顺便帮我解答一下
既然用了MatchCollection r = Regex.Matches(s,pattern); 那么该如何定位两个指定字符所在字符串中的位置呢?

match会捕获第一个匹配。而用matches才会捕获所有的匹配。
实例:string s = "HelloWorld";
string pattern = "o";
MatchCollection r = Regex.Matches(s,pattern);

string str = "helloworld";
Regex r = new Regex(@"(o)");
MatchCollection mc = r.Matches(str);

for (int i = 0; i < mc.Count; i++)
{
Match m = mc[i];
Response.Write("value:"+m.Groups[1].Value+" index:"+m.Groups[1].Index+"<br/>");
}

匹配次数可以在MatchCollection里面看到。

正则表达式是这样的,搜索到一个就停止了。

Match()是只匹配一项,一旦成功就直接返回
如果想匹配所有 可以使用Matches() 它就会搜索整个文本,返回的是一个MatchCollection集合对象,比如你要得到两个o的位置 就可以用它

那句话的意思是搜索第一个匹配的东西,它在hello中已经搜索到了匹配的项,所以下面的它就不会再去搜索了!你换一个hellworld,它就会搜索到world中去了