是否有正则表达式量词表示“x 或 y 重复"? [英] Is there a regex quantifier that says "either x or y repeats"?

查看:37
本文介绍了是否有正则表达式量词表示“x 或 y 重复"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想匹配一个字符串只包含恰好 7 位或 9 位的数字.

/^\d{7}$|^\d{9}$/

有没有另一种写法,类似于 /\d{7,8}/ 7 或 8 位数字?

Is there another way to write this, similar to /\d{7,8}/ for 7 or 8 digits?

推荐答案

这个怎么样:

/^\d{7}(?:\d{2})?$/

说明:

^      # Start of string
\d{7}  # Match 7 digits
(?:    # Try to match...
 \d{2} #  2 digits
)?     # ...optionally
$      # End of string

这篇关于是否有正则表达式量词表示“x 或 y 重复"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆