开发者

Replace two or more spaces with Regex in C#

开发者 https://www.devze.com 2023-02-12 23:22 出处:网络
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.

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, "&nbsp;");

// res == ab&nbsp;&nbsp;&nbsp;cde f
0

精彩评论

暂无评论...
验证码 换一张
取 消