Jason Brown Jason Brown - 1 month ago 6
C# Question

Regex Select ".." And not "..."

Essentially I have a string:
string str = "Hello.... My name is Steve.. I like Dogs."

I need to change occurrences of "..." or more periods into just 3. Any occurrences of 2 need to become 1.

Using

Regex.Replace(str)


Regex.Replace(str,"[.]{3,}","...")
works great at changing the groups greater then 3 to 3.
But I can't select groups of 2 "[.]{2}" because the groups of 3 are made up of 2...

My final String needs to look like this:
string str = "Hello... My name is Steve. I like Dogs."

Answer

Regex with negative lookahead and lookbehind:

(?<!\.)\.\.(?!\.)
Comments