简体   繁体   English

C#无效的文字字符

[英]C# Invalid Literal Characters

I created a working PCRE regex (for looking for PO Box address entries) that is throwing parser errors in C#. 我创建了一个有效的PCRE正则表达式(用于查找邮政信箱地址条目),该正则表达式正在C#中引发解析器错误。

The error is because of "\\." 该错误是由于“ \\”引起的。 and "\\s" characters in my pattern. 和“ \\ s”字符。

The error is: "Invalid literal character" 错误是:“无效的文字字符”

Here is the regex 这是正则表达式

^(?!.*p\.?o\.?\s+?box).*$ 

Here is the implementation 这是实现

[RegularExpression("^(?!.*p\.?o\.?\s+?box).*$", ErrorMessage = "We cannot ship to PO boxes")]

Would someone help me out with this? 有人可以帮我这个忙吗?

Thanks 谢谢

This because of backslash. 这是因为反斜杠。 Put your regex as verbatim string literal. 将您的正则表达式作为逐字字符串文字。 Single backslash inside double quotes would be treated as a escape sequence. 双引号内的单反斜杠将被视为转义序列。

@"^(?!.*p\.?o\.?\s+?box).*$"

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. 逐字字符串文字包含一个@字符,后跟一个双引号字符,零个或多个字符以及一个结束的双引号字符。 A simple example is @"hello". 一个简单的例子是@“ hello”。 In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. 在逐字字符串文字中,定界符之间的字符逐字解释,唯一的例外是引号-转义序列。 In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. 特别是,简单的转义序列以及十六进制和Unicode转义序列不在逐字字符串文字中处理。 A verbatim string literal may span multiple lines. 逐字字符串文字可能跨越多行。

Because the backslash is treated as escape character you either need to give your string as verbatim string: 由于反斜杠被视为转义字符,因此您需要将字符串作为逐字字符串:

@"^(?!.*p\.?o\.?\s+?box).*$"

Or you need to put two backslashes instead of one like following: 或者,您需要放置两个反斜杠,而不是如下所示的一个:

"^(?!.*p\\.?o\\.?\\s+?box).*$"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM