SuicideSheep
SuicideSheep

Reputation: 5550

C# Failed to understand Regex

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\\]*?$"

Upvotes: 0

Views: 59

Answers (2)

SpiderCode
SpiderCode

Reputation: 10122

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

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

Upvotes: 0

lc.
lc.

Reputation: 116458

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.

Upvotes: 8

Related Questions