regex - 正则表达式限制特定字符的一次出现
问题描述
我正在研究一个允许字符“x”和 0-9 之间的任何数字的正则表达式。
以下是规则。
- 整个字符串的长度必须为 4
- 只接受 0-9 或 'x'
- 必须正好有一个“x”
^(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 时,该规则必须关注。
更新规则
- 整个字符串的长度必须在 0 到 4 之间
- 只接受 0-9 或 'x'
- 不能有多个“x”
解决方案
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 orx
from the start up to the end of string\d*
- 0+ digitsx
- anx
\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).
推荐阅读
- rust - 特征对象的静态数组
- python-3.7 - 如何在 Python 3.7.4 和 openssl 1.1.1 中强制使用 TLSv1.2?
- python - 如何在没有 Internet 访问权限且没有 root 访问权限的 RHEL 4 企业版上安装 Python 3.6?
- html - 内部div中的滚动条,而父级只有最大高度
- git - 我需要一种 100% 确定的方法来使我的 GitHub 分叉和克隆与原始版本相同吗?
- mysql - 在 mySQL 中运行的奇怪正则表达式
- python-3.x - 从引发错误的同一点继续执行脚本
- .net - [MsTeams][BotFrameworkV4][Adaptive Card ] 团队中可滚动的自适应卡片
- regex - 如何通过 TYPO3 的重定向模块重定向以特定路径开头的 URL?
- android - 处理程序 - PostDelayed 方法“破坏”其余(块)代码?