C#正则表达式 - 不匹配我的字符串 [英] C# regex - not matching my string

查看:533
本文介绍了C#正则表达式 - 不匹配我的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用.NET 2.0与C#的WinForms。我有正则表达式的一个大问题。我想一个冒号在一个简单的字符串添加到4个或更多字母的单词。它应该只追加冒号一次,之后的代码不应该附加任何更多。

I'm using NET 2.0 with WinForms on C#. I am having a big problem with regex. I'm trying to add a colon to 4 or more letter words in a simple string. It should only append the colon once, after that the code shouldn't append any more.

Regex lbls = new Regex(@"^\s*(?<lbl>[A-Za-z0-9_]{4,})", RegexOptions.Multiline); // Use a regex to obtain all 4 letter words in string
MatchCollection matches = lbls.Matches(text); // text is my string

foreach (Match m in matches)
{
  string mm = m.Groups["lbl"].Value; // Matches are stored in this group.
  if (!Regex.IsMatch(text, @"^\s*\b" + mm + @":\b", RegexOptions.Multiline))
  {
    text = Regex.Replace(text, @"\b" + mm + @"\b", mm + ":", RegexOptions.Multiline);
  }
}



假设字符串为测试。这意味着输出应该是TEST:这是。但是,如果代码运行一次,文应保持TEST:但事实并非如此,这是TEST ::来代替。不断添加冒号。为什么是这样?我如果语句看起来完全正确的。

Suppose the string is "TEST". That means the output should be "TEST:" which it is. However if code is run once more, the text should remain "TEST:" but it does not and it is "TEST::" instead. Colons keep being added. Why is this? My if statement looks fully correct.

推荐答案

在运行代码的第一次,你要搜索的价值TEST在输入(这是简单的TEST),并用TEST替换它并附加一个冒号到结束

The first time you run your code, you're searching for the value "TEST" in your input (which is simply "TEST") and replacing it with "TEST" and appending a colon to the end.

因此在第一次迭代后,其结果将是TEST。

So after the first iteration, the result will be "TEST:".

在运行代码的第二次,你正在寻找在你的输入值TEST(也就是现在的TEST ),并用测试和附加冒号到端代替。

The second time you run your code, you're searching for the value "TEST" in your input (which is now "TEST:") and replacing it with "TEST" and appending a colon to the end.

所以第二迭代后,其结果将是TEST ::

So after the second iteration, the result will be "TEST::".

好像你只需要附加一个冒号,只当没有冒号存在(也许?)结束。

Seems like you only want to append a colon to the end only when no colon exists(maybe?).

尝试改变你的如果行此...

Try changing you "if" line to this...

if ( !Regex.IsMatch( text , @"\b" + mm + @"\b:" , RegexOptions.Multiline ) )

这篇关于C#正则表达式 - 不匹配我的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆