首页 > 解决方案 > 正则表达式限制特定字符的一次出现

问题描述

我正在研究一个允许字符“x”和 0-9 之间的任何数字的正则表达式。

以下是规则。

^(x|[0-9])(x|[0-9])(x|[0-9])(x|[0-9])$

我目前的正则表达式只能使用规则 1 和 2,但它不会过滤掉那些有多个“x”的

x000 //ok
xxxx //ok , but should be not ok
23xx //ok , but should be not ok
a90d //not ok
11x1 //ok
x213 //ok

示例正则表达式编辑器在这里

由于正则表达式将用于在 keyup 中进行验证,因此当用户键入一到四个 keyup 时,该规则必须关注。

更新规则

标签: regex

解决方案


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


推荐阅读