Leon Armstrong
Leon Armstrong

Reputation: 1303

Regex on limiting one occurrence of particular character

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

Upvotes: 4

Views: 2110

Answers (3)

Bohemian
Bohemian

Reputation: 425378

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

^(?=\d*x\d*$).{4}$

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

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+ 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).

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522741

One option uses lookahead to handle the one x requirement:

^(?=.*x)(?!.*x.*x)[0-9x]{4}$

See the regex demo.

Demo

Upvotes: 0

Related Questions