Reputation: 59
so I have an input field where the client can type in numbers from 1-10 in length with a wildcard with at least 1 number as prefix. (* is not allowed, while 1* would be)
The Wildcard can be set in the middle of the string, BUT the overall max length of the expression is 10. At this point I received this result by the following expression:
^([ ,;]?(?=.{1,10}$)((\d{1,9})(\*?)(\d{0,9}?))[ ,;]?)$
Now the problem. As you can see in the expression, seperators SPACE, COMMA & SEMI-COLON are allowed at the beginning or at the end of a string, because the client can input multiple numbers in that combination. [ ,;]?
But he can't because of the max length of 10 (?=.{1,10}$)
.
On the other hand, if I remove the max length limit, then you can input one number longer than 10 (exactly max 19 characters right now) 123456789*123456789
-> would be allowed without the limitation.
Is there any way to limit the expression that way, that the character length in between the seperators must be 10 absolute MAX length, but overall the max length can longer to input more numbers?
Upvotes: 1
Views: 115
Reputation: 75860
Maybe:
^(?:\d(?=\d*\*?\d*(?:[ ,;]|$))[\d*]{0,9}(?:[ ,;]|$))+$
See the online demo
Since you want to start a number with at least a single digit, the following would match;
^
- Start of string ancor.(?:
- Open 1st non-capture group.
\d
- Match a single digit.(?=
Open positive lookahead.
\d*\*?\d*
- Any amount of digits, an optional wildcard, and again any amount of digits (to only allow a single wildcard).(?:
- Open nested 2nd non-capture group.
[ ,;]|$
- Match any of the characters in the character class or then end of the string.)
- Close 2nd non-capture group.)
- Close positive lookahead.[\d*]{0,9}
- Match 0-9 characters from the character class (digits or wildcards).(?:
- Open 3rd non-capturing group.
[ ,;]|$
- Match any of the characters in the character class or then end of the string.)
- Close 3rd non-capturing group.)
- Close 1st non-capturing group.+
- Repeat 1st non-capturing group at least once.$
- End string ancor.EDIT1: The above would allow for a trailing comma, semi-colon or space. If you want to avoid that you could use:
^(?:\d(?=\d*\*?\d*[ ,;])[\d*]{0,9}[ ,;])*\d(?=\d*\*?\d*$)[\d*]{0,9}$
See the online demo
EDIT2: The above would allow only a single wildcard per number. If your intention was such that multiple should be allowed (but simply not after one another, you could try:
^(?:\d(?!.*\*\*.*[ ,;])[\d*]{0,9}[ ,;])*\d(?!.*\*\*.*$)[\d*]{0,9}$
See the online demo
EDIT3: If for some reason you decide you do want to allow consecutive wildcards (but still start with atleast a single digit), you could opt for:
^(?:\d[\d*]{0,9}[ ,;])*\d[\d*]{0,9}$
See the online demo
Upvotes: 1