Steve N
Steve N

Reputation: 319

Regular Expression Space character not working

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

Answers (4)

Kavindu Dodanduwa
Kavindu Dodanduwa

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

Gavin Jackson
Gavin Jackson

Reputation: 2047

As per other answers....

  • Use \s instead of /s
  • You shouldn't need to square bracket the [\s], because it already implies a complete class of characters.

Also...

  • In most languages, you probably don't want to use double quotes "..." as delimiters to the Regex, since this might be interpolating the \s before the pattern is applied. It's certainly worth a try.
  • Use a trailing quantifier \s* or \s? to allow the space to be optional.

Upvotes: 0

Chris
Chris

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]$"

Regexper

Upvotes: 1

Bas
Bas

Reputation: 27085

Use the \s token for whitespace instead of /s.

Some handy tools to speed up regex development:

  • regexr.com helps with syntax and provides realtime testing
  • regexpr.com (yes I know :)) visualizes your expression.

Upvotes: 0

Related Questions