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
sample regex editor here
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
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).
Use a look ahead for the “only 1 x” condition:
^(?=\d*x\d*$).{4}$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With