简体   繁体   中英

C# Invalid Literal Characters

I created a working PCRE regex (for looking for PO Box address entries) that is throwing parser errors in C#.

The error is because of "\\." and "\\s" characters in my pattern.

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". 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. 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).*$"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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