Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

regex - Regular expression to allow backslash in C#

Can anyone provide me with regex for validating string which only should not allow any special characters except backslash. I tried

var regexItem = new Regex("^[a-zA-Z0-9\ ]*$");

But it doesn't seem to work

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Backslashes need to be escaped in regular expressions - and they also need to be escaped in C#, unless you use verbatim string literals. So either of these should work:

var regexItem = new Regex(@"^[a-zA-Z0-9\ ]*$");
var regexItem = new Regex("^[a-zA-Z0-9\\ ]*$");

Both of these ensure that the following string content is passed to the Regex constructor:

^[a-zA-Z0-9\ ]*$

The Regex code will then see the double backslash and treat it as "I really want to match the backslash character."

Basically, you always need to distinguish between "the string contents you want to pass to the regex engine" and "the string literal representation in the source code". (This is true not just for regular expressions, of course. The debugger doesn't help by escaping in Watch windows etc.)

EDIT: Now that the question has been edited to show that you originally had three backslashes, that's just not valid C#. I suspect you were aiming for "a string with three backslashes in" which would be either of these:

var regexItem = new Regex(@"^[a-zA-Z0-9\ ]*$");
var regexItem = new Regex("^[a-zA-Z0-9\\\ ]*$");

... but you don't need to escape the space as far as the regular expression is concerned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...