C# - Regex.Replace - 无法弄清楚为什么换行符没有被替换

标签 c# regex

我还不确定为什么尝试将否定字符类与 Regex.Replace 一起使用不会用空格替换换行符。

下面是一些示例代码:

namespace ConsoleApplication1
{
    class Program
       {
        static void Main(string[] args)
          {

            string testInput = "This is a test. \n This is a newline. \n this is another newline. This is a, comma";



            Console.WriteLine(testInput);


            //get rid of line breaks and other letters not allowed
            string commentFix = Regex.Replace(testInput, @"[^A-Z\sa-z\.0-9\-\:\;\$]", " ");
            commentFix = "\"" + commentFix + "\"";


            Console.WriteLine("\n");

            Console.WriteLine(commentFix);
            Console.ReadLine();


          }
      }
}

这个的输出是:

This is a test.
 This is a newline.
 this is another newline. This is a, comma

"This is a test.
 This is a newline.
 this is another newline. This is a  comma"

有什么想法吗? (谢谢,这是我的第一个问题!)

最佳答案

\s 匹配换行符,因为它在 negated character class 中, 换行符不会被删除。

查看更多details on what \s matched at MSDN :

\f - The form feed character, \u000C.
\n - The newline character, \u000A.
\r - The carriage return character, \u000D.
\t - The tab character, \u0009.
\v - The vertical tab character, \u000B.
\x85 - The ellipsis or NEXT LINE (NEL) character (…), \u0085.
\p{Z} - Matches any separator character.

所以,如果你想删除空格,只需取出 \s (我猜你需要替换与一个空格匹配的多个字符,添加 + 这将匹配它量化的模式的一次或多次出现):

[^A-Za-z.0-9:;$-]+

参见 regex demo

另请注意,您不必在字符内转义 .:;$类,如果 - 位于字符类的开头/结尾,则无需转义。

如果您打算匹配空格但 CR 和 LF 除外,请使用 [^\S\r\n]:[^A-Z\S\r\na-z.0-9:;$-]+ .这里,[^\S] 匹配一个空格,但是 \r\n 在否定字符类中,所以它们不匹配。

关于C# - Regex.Replace - 无法弄清楚为什么换行符没有被替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36410730/

相关文章:

javascript - 使用 jQuery 的正则表达式问题

python - 如何将所有 6 个字母的拉丁词提取到一个列表中?

c# - 在 OpenXML (excel) 中创建自定义列宽

c# - 在 C# .NET 中用单个值初始化整数数组

c# - 我可以通过 C# 中的堆栈跟踪获取方法局部变量吗?

c# - try catch block

javascript - 正则表达式查找与两个字符串匹配的模式,两个字符串之间的空格数为 'x'

c# - 捕获用户触摸的 x 和 y,iOS Xamarin Forms

javascript - 为什么 .test() 函数对于 onclick 行为不可靠?

ios - Swift 正则表达式匹配 unicode