Home > other >  Optional extra character in regex character class
Optional extra character in regex character class

Time:12-22

I am using regex to match a String starting with XY and then 9 digits, like:

XY123456789

I am using this regex:

XY[0-9]{9}

Easy. But now I want to allow a an optional space in those digits.

So, the regex should match:

XY123456789
XY123 456789
XY1234567 89

I can use XY[0-9 ]{9,10}. But I just want to allow a maximum of one spaces, and only nine digits. So, the regex should not match:

XY1234567891
XY123 456 78

So XY([0-9] ?){9} or XY[0-9] ?[0-9] ?[0-9] ?[0-9] ?[0-9] ?[0-9] ?[0-9] ?[0-9] ?[0-9] doesn't work either.

Any ideas? Is there any way to specify the number of occurrences inside the character class, something like XY[[0-9]*[ ]?]{9} for example?

(In my specific case I'm using Java regex if that matters.)

CodePudding user response:

You might use

^XY(?!\d*\h\d*\h)(?:\d(?:\h?\d){8})$

The pattern matches:

  • ^ Start of string
  • XY Match literally
  • (?!\d*\h\d*\h) Negative lookahead, assert not 2 spaces
  • (?:\d(?:\h?\d){8}) Match 9 digits with an optional space
  • $ End of string

Regex demo

In Java

String regex = "^XY(?!\\d*\\h\\d*\\h)(?:\\d(?:\\h?\\d){8})$";
  • Related