Philipp Silbernagl
Philipp Silbernagl

Reputation: 11

Regular Expression positive lookbehind

I would like to create a regex, that allowes the following patterns:

1234
1234567
123456789
12345678900-
12345678900-123456

It should be possible to only insert numbers and only one hyphen is allowed.

I tried with the following regex:

^[0-9]{1,11}(?(?<=\d{11})[-]?|)[0-9]{6}

It should not be possible to have 11 characters without the hyphen at the end(12345678900 is wrong).

Unfortunatly it didnt work as I intended.

Upvotes: 1

Views: 63

Answers (2)

The fourth bird
The fourth bird

Reputation: 163497

You can match 1-10 digit and optionally match 1 digit followed by - and 6 digits.

^\d{1,10}(?:\d?-(?:\d{6})?)?$
  • ^ Start of string
  • \d{1,10} Match 1-10 digits
  • (?: Non capture group
    • \d?- Match a single optional digit and -
    • (?:\d{6})? Match optional 6 digits
  • )? Close non capture group and make it optional
  • $ End of string

Regex demo

Another variation could be matching 1-10 digits or match 11 digits with a hyphen and optionally 6 digits if the hyphen should only possible after 11 digits.

^(?:\d{1,10}|\d{11}-(?:\d{6})?)$

Regex demo

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627272

You can use

^[0-9]{1,11}(?:(?<=[0-9]{11})-(?:[0-9]{6})?)?$
^\d{1,11}(?:(?<=\d{11})-(?:\d{6})?)?$

See the regex demo. Using \d is possible in case it matches ASCII digits in your regex flavor or you do not care if \d matches all possible Unicode digit chars or not.

Details:

  • ^ - start of string
  • [0-9]{1,11} - one to eleven digits
  • (?:(?<=[0-9]{11})-(?:[0-9]{6})?)? - an optional occurrence of
    • (?<=[0-9]{11}) - immediately to the left there must be 11 digits
    • - - a hyphen
    • (?:[0-9]{6})? - an optional occurrence of six digits
  • $ - end of string.

Upvotes: 0

Related Questions