Reputation: 1303
I am working on a regex that allow a character 'x' and any digit from 0-9.
below are the rules.
^(x|[0-9])(x|[0-9])(x|[0-9])(x|[0-9])$
My current regex only able rule 1 and 2, but it doesn't filter out those with more than one 'x'
x000 //ok
xxxx //ok , but should be not ok
23xx //ok , but should be not ok
a90d //not ok
11x1 //ok
x213 //ok
Since the regex will be used for validation in keyup so the rule must concern when the user type from one to four keyup.
Updated rules
Upvotes: 4
Views: 2110
Reputation: 425378
Use a look ahead for the “only 1 x” condition:
^(?=\d*x\d*$).{4}$
Upvotes: 2
Reputation: 627498
You may use
/^(?=[0-9x]{4}$)[0-9]*x[0-9]*$/
or
/^(?=[\dx]{4}$)\d*x\d*$/
Details
^
- start of string(?=[\dx]{4}$)
- a positive lookahead checking that there are exactly 4 digits or x
from the start up to the end of string\d*
- 0+ digitsx
- an x
\d*
- 0+ digits$
- end of string.See the regex demo
Note that in this case, you may even reduce the whole pattern to
/^(?=.{4}$)\d*x\d*$/
^^^^^^^^^
to just check the length of the string without checking the type of chars (since digits and x
are non-linebreak chars).
Upvotes: 3
Reputation: 522741
One option uses lookahead to handle the one x
requirement:
^(?=.*x)(?!.*x.*x)[0-9x]{4}$
See the regex demo.
Upvotes: 0