regex - 无特定顺序的字符和数字的正则表达式(但最多 10 个数字)
问题描述
所以我有一个字符串(带空格):
John Doe
最多可以混合 10 个数字
John Doe 123456789
没有特别的顺序:
1234john Doe567890
我试过像这样混合字符、空格和数字:
([A-Za-z ])([0-9]){10}
但我没有击中目标
我如何编写正则表达式来验证这一点?
解决方案
尝试这个
^(?=(?:\D*\d){0,10}\D*$)
解释:
^ # Beginning of string, BOS
# Lookahead assertion
(?=
# Note this group is designed
# so that it is the only place
# a digit can exist.
(?: # Group
\D* # Optional, any amount of non-digits
\d # Required, a single digit
){0,10} # End group, do 0 to 10 times
# Example:
# - If this group runs 0 times, no digits were in the string.
# - If this group runs 4 times, 4 digits are in the string.
# - Therefore, min digits = 0, max digits = 10
\D* # Finally, and optionally, any amount of non-digits
$ # End of string, EOS
)
推荐阅读
- android-studio - 为什么在 android studio 更新后出现“manifestOutputDirectory”错误?
- python - Python - PySimpleGUI - 无法选择日历输入
- java - 我有这个错误:“无法将 java.lang.String 类型的对象转换为 com.flashpub.flash.imageSection 类型”,我不知道为什么
- javascript - 如何使用 Electron.js 彼此相邻显示自定义 Windows 消息框按钮
- android - 我怎样才能在android中制作一个完美的正方形?
- ios - 如何在运行时更改 UIMenu 内的 UIAction 的状态?
- c++ - 在 Xcode C-lang 中链接库
- javascript - 为什么我的应用脚本代码将电子表格复制到谷歌驱动器的根目录以及特定目录?
- docker - Dockerfile:来自守护进程的错误响应:OCI 运行时创建失败:container_linux.go:349
- java - 在方法重载中,方法解析发生在编译时还是运行时?