简体   繁体   中英

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.

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

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:

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

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM