I am horrible with Regex stuff. I would like to use a regular expression in C# to turn any two or more spaces into non-breaking spaces. I would like to leave single spaces alone.
Sample Sample
Woul开发者_Go百科d produce
Sample Sample
But
Sample Sample
Wouldn't be affected.
Any ideas?
Thanks in advance.
You can use a MatchEvaluator
as the replacement argument. In C# 3.0 or newer you can use a lambda function:
s = Regex.Replace(s, " {2,}", x => x.Value.Replace(" ", " "));
It's based on zero-width positive lookahead and lookbehind assertions.
MSDN
var rx = new Regex(" (?= )|(?<= ) ");
var str = "ab cde f";
var res = rx.Replace(str, " ");
// res == ab cde f
精彩评论