C# 使用正则表达式时遇到异常问题
我有一行代码:C# 使用正则表达式时遇到异常问题,c#,regex,winforms,C#,Regex,Winforms,我有一行代码: textBox1.Text = Regex.Replace(textBox1.Text, "(?:\r\n)+", " \r\n"); 这基本上是在换行之前向行添加一个双空格键: 输入: a b c d e a //<--- Double spacebar after the 'a' character b //<--- Double spacebar after the 'b' character c //<--- Double spaceba
textBox1.Text = Regex.Replace(textBox1.Text, "(?:\r\n)+", " \r\n");
这基本上是在换行之前向行添加一个双空格键:
输入:
a
b
c
d
e
a //<--- Double spacebar after the 'a' character
b //<--- Double spacebar after the 'b' character
c //<--- Double spacebar after the 'c' character
d //<--- Double spacebar after the 'd' character
e
输出:
a
b
c
d
e
a //<--- Double spacebar after the 'a' character
b //<--- Double spacebar after the 'b' character
c //<--- Double spacebar after the 'c' character
d //<--- Double spacebar after the 'd' character
e
但它不起作用
输入:
a
b
c //<---- Double spacebar before the line break to check if it ignores it
d
e
a
B
c/正确的正则表达式:(?:)?\r\n
需要考虑的几点:
如果确实希望将多个换行符“折叠”为一个,作为原始正则表达式提示(带+号),则将我的整个正则表达式包装在一个非捕获组中,并加上加号:(?:(?:)?\r\n)+
是的,我的正则表达式将用完全相同的东西替换双空格换行符,但这没关系,而且比添加额外空格要好,正如您所提到的
将同一个字符多次添加到字符类(使用[括号])没有任何意义。因此[]
与[]
相同,意思是“匹配一个空格或一个空格或一个空格…”
哦,好的,非常感谢:)现在可以了,谢谢你解释得这么清楚,我现在明白了,再次感谢!!!