0

I'm trying to validate a textbox to accept just alpha-numeric and "\" character, something like this: Testing123\ will return true. Below is what I've tried so far:

"^[a-zA-Z0-9]*?$"

The above expression can accept alpha-numeric with no restriction of number of letters which working fine.

If not mistaken, "\" behave as escape character and so I tried below expression but it's throwing unterminated expression exception:

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

2 Answers 2

8

You're going to have to double-escape the backslash character because you actually need to send two backslashes to the Regex parser:

string example1 = "^[a-zA-Z0-9\\\\]*?$"; //two backslash characters assigned to the string

The first level of escaping is for the compiler, and the second level for the Regex - the backslash is an escape character, both in C# and Regex (that is, things like \n have meaning to the C# compiler and things like \s have meaning to the Regex parser)

Or you can use the @ literal marker:

string example2 = @"^[a-zA-Z0-9\\]*?$" //same here but the @ symbol saves us the headache

Why you're seeing "unterminated expression" is the Regex parser sees ^[a-zA-Z0-9\]*?$ - that is, a beginning-of-line marker followed by a character class containing uppercase, lowercase, digits, and the characters ], *, ?, $, which is never closed because there's no closing bracket.

Sign up to request clarification or add additional context in comments.

2 Comments

Correct me if I'm wrong, if now the case change to ? instead of \ then the correct expression would be "^[a-zA-Z0-9\\\?]*?$" instead?
Yes and no: a)you don't need /? because it isn't an escape sequence and the compiler doesn't have a special meaning for ?, so we're down to "^[a-zA-Z0-9\\?]*?$". And b)you actually don't need to escape the ? once inside a character class, so sending a backslash to the Regex engine is superfluous, and you can simply use "^[a-zA-Z0-9?]*?$"
0

Put one more back slash in your regular expression as shown below :

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

2 Comments

That's two more, and your answer been given by lc. Anyway, thanks for that :)
that's two more for the compiler perspective :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.