Home > Software design >  Regex match pattern, space and character
Regex match pattern, space and character

Time:08-24

^([a-zA-Z0-9_-] )$ matches:

BAP-78810
BAP-148080

But does not match:

B8241066 C
Q2111999 A
Q2111999 B

How can I modify regex pattern to match any space and/or special character?

CodePudding user response:

For the example data, you can write the pattern as:

^[a-zA-Z0-9_-] (?: [A-Z])?$
  • ^ Start of string
  • [a-zA-Z0-9_-] Match 1 chars listed in the character class
  • (?: [A-Z])? Optionally match a space and a char A-Z
  • $ End of string

Regex demo

Or a more exact match:

^[A-Z] -?\d (?: [A-Z])?$
  • ^ Start of string
  • [A-Z] -? Match 1 chars A-Z and optional -
  • \d (?: [A-Z])? Matchh 1 digits and optional space and char A-Z
  • $ End of string

Regex demo

CodePudding user response:

Whenever you want to match something that can either be a space or a special character, you would use the dot symbol .. Your regex pattern would then be modified to:

^([a-zA-Z0-9_-]) .$

This will match the empty space, or any other character. If you want to match the example provided, where strictly one alphabetical, numer character will follow the space, you could include \w such that:

^([a-zA-Z0-9_-]) .\w$

Note that \w is equivalent to [A-Za-z0-9_]

Further, be careful when you use . as it makes your pattern less specific and therefore more likely to false positives.

CodePudding user response:

I suggest using this approach

^[A-Z][A-Z\d -]{6,}$

The first character must be an uppercase letter, followed by at least 6 uppercase letters, digits, spaces or -.

I removed the group because there was only one group and it was the entire regex.

You can also use \w - which includes A-Z,a-z and 0-9, as well as _ (underscore). To make it case-insensitive, without explicitly adding a-z or using \w, you can use a flag - often an i.

  • Related