Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex on limiting one occurrence of particular character

Tags:

regex

I am working on a regex that allow a character 'x' and any digit from 0-9.

below are the rules.

  • whole string must be in length of 4
  • only accept 0-9 or 'x'
  • must have exactly one 'x'

^(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

  • whole string must be in length from 0 to 4
  • only accept 0-9 or 'x'
  • cannot have more than one 'x'
like image 814
Leon Armstrong Avatar asked Sep 05 '25 03:09

Leon Armstrong


2 Answers

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+ digits
  • x - 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).

like image 151
Wiktor Stribiżew Avatar answered Sep 07 '25 21:09

Wiktor Stribiżew


Use a look ahead for the “only 1 x” condition:

^(?=\d*x\d*$).{4}$
like image 39
Bohemian Avatar answered Sep 07 '25 21:09

Bohemian