(!!!公告!!!)正则表达式专用讨论区(精华)

heavenkiller 2003-11-15 01:09:15
我来提第一个问题!
******************************
请看下面一段代码:
string word="!!heaven!killer aaa!";
//string word="!!";
string strReg=@"!\S*!";//pick max character?
Regex r=new Regex(strReg);
Match m=r.Match(word);
Console.WriteLine("Is Matched:"+m.Success.ToString());
for(int i=0;i<m.Groups.Count;i++)
{
Console.WriteLine("Groups["+i+"] value"+m.Groups[i].Value);
for(int j=0;j<m.Groups[i].Captures.Count;j++)
{
Console.WriteLine(m.Groups[i].Captures[j].Value);
}
}

应该有两个匹配!!和!!heaven!,但为什么只有!!heaven! 呢  ?
...全文
29 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
saucer 2003-11-15
  • 打赏
  • 举报
回复
"*" is greedy, it will grab anything it can, try to use "*?", also, once it matches "!..!", it will start from the character the last "!", so in your case, even if you use "!\S*?!", it will not match "heaven", also, you need to use Matches, also see an example for "$":

string[] slist ={"!!heaven!killer aaa!", "!!!heaven!!ddkiller aaa!", "abc"};
//string word="!!";
string strReg=@"!\S*?!";//pick max character?

Regex r=new Regex(strReg);
foreach (string word in slist)
{
MatchCollection mc=r.Matches(word);
Console.WriteLine("{0} matches: {1}", word, mc.Count > 0);
foreach (Match m in mc)
Console.WriteLine(m.Value);
}

r = new Regex("[^!]+!$");
foreach (string word in slist)
{
MatchCollection mc=r.Matches(word);
Console.WriteLine("{0} matches: {1}", word, mc.Count > 0);
foreach (Match m in mc)
Console.WriteLine(m.Value);
}
heavenkiller 2003-11-15
  • 打赏
  • 举报
回复
第二个问题:
$是怎样用的,能否用完整的代码举个例子?

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧