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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...