Regex 正则表达式将2个或多个替换为2个或多个
我想用多个Regex 正则表达式将2个或多个替换为2个或多个,regex,Regex,我想用多个替换多个空格&nbps,但如果只有1,我想将其作为普通空间保留 测试用例: input | desired output --------------------------- a test | a test a test | a test a test | a test 在这种特殊情况下,我也希望保留换行符,稍后我将用替换它,因此我只使用作为我的正则表达式尝试
替换多个空格&nbps代码>,但如果只有1,我想将其作为普通空间保留
测试用例:
input | desired output
---------------------------
a test | a test
a test | a test
a test | a test
在这种特殊情况下,我也希望保留换行符,稍后我将用
替换它,因此我只使用
作为我的正则表达式尝试
到目前为止,我只得到了/{2,}/g
替换为
,但我不知道如何使替换与模式中的{}
找到的计数匹配。有没有办法做到这一点,或者通过一些迭代过程更好
在本例中,我使用的是C#:Regex.Replace(输入,@“{2,}”,“”)
您可以使用基于查找的Regex:
(?<= ) | (?= )
正则表达式详细信息:
Regex.Replace(input, @"(?<= ) | (?= )", " ")
(?由于您希望替换每个带有更多空格的空格,您可以使用环视来定位每个此类空格,并将其替换为
。下面是正则表达式
(?= )|(?<= )
这可能是技术上最有效的方法:
\B|\B
演示:
说明:
- 对于某些上下文,
\b
匹配单词边框,基本上是单词字符(字母和数字)和非单词字符之间的任意点
\B
是对\B
的否定,这意味着它匹配\B
不匹配的所有内容,反之亦然
- 因此,上面的模式要么匹配A.)相同类型的两个字符之间的一个点,后跟一个空格,要么匹配B.)相同类型的两个字符之间的一个空格,后跟一个点
string pattern = @" (?= )|(?<= ) ";
string substitution = @" ";
string input = @"a test
a test
a test";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
Console.WriteLine(result);
a test
a test
a test