1

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 Xs 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.

Length restriction: 0 to 25 characters.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
legionth
  • 87
  • 6

3 Answers3

1

As far as I understand your needs, this would do the job:

^\d+(?:x+|\*)?$

New version according to question edit:

^[+#]?\d*(?:x+|\*)?$
Toto
  • 89,455
  • 62
  • 89
  • 125
0

Based on your new update:

^(?=.)[+#*]?\d*?(?:X+|\*)?$

Live demo

Explanation:

^           # Asserts beginnig of input string
(?=.)       # Positive looakehad - input string length should be at least 1
[+#*]?      # Optional symbols 
\d*?        # Optional digits (any number)
    (?:         # Start of non-capturing group (a)
        X+          # Any number of X
        |           # Or
        \*          # A single *
    )?          # End of non-capturing group (a) - optional
$           # End of string
revo
  • 47,783
  • 14
  • 74
  • 117
0

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).
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Please note I used the `D` modifier in the regex, it will make sure the `$` matches the very end of the string. Without it, `$` may match before the final newline symbol which might not be good when validation is performed. Note you can also replace `$` with `\z` anchor to achieve the same behavior. – Wiktor Stribiżew Aug 31 '16 at 11:28