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.
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]$"
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]$");
Use the \\s
token for whitespace instead of /s
.
Some handy tools to speed up regex development:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.