legionth legionth - 3 months ago 11
PHP Question

Regex to find evaluate number pattern

I'm trying to create a regular expression to match on a specific given number pattern.

The patterns are:

123456

1234XX

1234*


Not allowed are:
A combinations like:
1234*X
or
1234X*

Or a multiple
*
:
1234**


I already tried this expression:

/^[\\+\\#\\*0-9]{0,25}[X]*$/


But here I got the multiple
*
and
1234*X
as valid expressions.

Does anyone have an idea of a proper soultion or a way to a solution?

Edit:
Ok, I think I should clearify the rules.

The regex should match any given number:

012345
+12345
#1234525


But also match for strings with a
X
in it.

12345X
12345XX
1234XXXXXX
XXXXXX


The
X
s should always stand on the end of the string.

A single
*
should only be allowed at the end of the string.

1234*
1234556*
1*


Multiple
*
aren't allowed. Only one
*
at the end of the string.

The combination of
X
and
*
are not allowed.
1234X*
or
12345*X
are not allowed.

Answer

You can use

'~^(?=.{0,25}$)[+#]?\d*(?:X*|\*?)$~D'

See regex demo

This will make sure the whole string is 0 to 25 chars long, and will only allow one * at the end of the string, and zero or more X can only follow 0 or more digits.

Details:

  • ^ - start of string
  • (?=.{0,25}$) - a positive lookahead checking the whole string length (must be from 0 to 25 chars long)
  • [+#]? - one or zero + or #
  • \d* - zero or more digits
  • (?:X*|\*?) - a non-capturing group matching either of the 2 alternatives:
    • X* - zero or more X symbols
    • | - or...
    • \*? - one or zero * symbols
  • $ - end of string (better replace it with \z to ensure no newline at the end is accepted, or just add D modifier).
Comments