I’m not sure if “token replace” is the right phrase but here is what i’m trying to do:
In a string if I find two or more consecutive white spaces (\s) aka – spaces, new lines, tabs etc. I want to replace whatever it matched with only one instance of itself.
Example:
a b b
would become
a b b
and:
a
b
c
Would become:
a
b
c
Can this be done using .net regex?
You’ll need to use this if you want to correctly replace double new-lines as well as spaces:
The
\1will look for the character(s) matched by the group(\s|\r\n), and the$1in the replacement string will replace the match with just a single instance of the group.If you want to replace more than one duplicate (i.e. 3 in a row) with a single instance, you’ll need to use
@"(\r\n|\s)\1+"as the pattern, but a side effect of this will be:will be reduced to: