我还不确定为什么尝试将否定字符类与 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/