Reputation: 319
My Regex is for a canadian postal code and only allowing the valid letters:
Regex pattern = new Regex("^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][/s][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$");
The problem I am having is that I want to allow for a space to be put in between the each set but cannot find the correct character to use.
Upvotes: 1
Views: 234
Reputation: 13059
If you are simply searching for space use \s
To provide the escape sequence character \
use @
verbitm literal character as below in the given example.
Regex pattern = new Regex(@"^[ABCEGHJKLMNPRSTVXY][0-9]\s[ABCEGHJKLMNPRSTVWXYZ[0-9]\s[ABCEGHJKLMNPRSTVWXYZ][0-9]$");
As pointed out in the comments, if space is optional you can use ?
quantifier as below.
Regex pattern = new Regex(@"^[ABCEGHJKLMNPRSTVXY][0-9]\s?[ABCEGHJKLMNPRSTVWXYZ[0-9]\s?[ABCEGHJKLMNPRSTVWXYZ][0-9]$");
Upvotes: 1
Reputation: 2047
As per other answers....
\s
instead of /s
[\s]
, because it already implies a complete class of characters.
Also...
"..."
as delimiters to the Regex, since this might be interpolating the \s
before the pattern is applied. It's certainly worth a try.\s*
or \s?
to allow the space to be optional. Upvotes: 0
Reputation: 788
You've got a forward-slash instead of a backslash in your regular expression for whitespace (\s). The following regex should work.
@"^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][\s][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$"
Upvotes: 1
Reputation: 27085
Use the \s
token for whitespace instead of /s
.
Some handy tools to speed up regex development:
Upvotes: 0