简体   繁体   中英

C# regex - not matching my string

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);
  }
}

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.

尝试用$1:替换^([A-Za-z0-9_]{4})(?!:) ,其中$1是第一组。

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.

So after the first iteration, the result will be "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.

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 ) )

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