1

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

? Not quite sure what you mean.
The regex matches 4 alphanumeric characters from the beginning of input, captures them, and checks that they are not followed by a column.
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 ) )

3 Comments

Yes, but I'm confused. Where is the problem? Also, am I not searching for the value "TEST:" in the first iteration, not "TEST"? There's a colon in the search too.
I just updated my answer to address your comment. I believe moving the colon in your IF statement should get you what you need... I hope.
Yeah, that fixed it and I see the problem now. I placed the : INSIDE the word boundary instead of outside, silly mistake. Thanks for pointing that out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.