dnclem
dnclem

Reputation: 2838

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.

Upvotes: 1

Views: 1905

Answers (2)

Steve Dignan
Steve Dignan

Reputation: 8530

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

Upvotes: 1

fge
fge

Reputation: 121712

Try and replace ^([A-Za-z0-9_]{4})(?!:) with $1:, where $1 is the first group.

Upvotes: 2

Related Questions