匹配特定长度 x 或 y [英] Match specific length x or y

查看:43
本文介绍了匹配特定长度 x 或 y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个长度为 X 或 Y 字符的正则表达式.例如,匹配长度为 8 或 11 个字符的字符串.我目前是这样实现的:^([0-9]{8}|[0-9]{11})$.

I'd like a regex that is either X or Y characters long. For example, match a string that is either 8 or 11 characters long. I have currently implemented this like so: ^([0-9]{8}|[0-9]{11})$.

我也可以将其实现为:^[0-9]{8}([0-9]{3})?$

我的问题是:我可以在不复制 [0-9] 部分的情况下使用这个正则表达式(这比这个简单的 \d示例)?

My question is: Can I have this regex without duplicating the [0-9] part (which is more complex than this simple \d example)?

推荐答案

有一种方法:

^(?=[0-9]*$)(?:.{8}|.{11})$

或者,如果您想先进行长度检查,

or alternatively, if you want to do the length check first,

^(?=(?:.{8}|.{11})$)[0-9]*$

这样,复杂的部分就只有一次,还有一个通用的 . 用于长度检查.

That way, you have the complicated part only once and a generic . for the length check.

说明:

^       # Start of string
(?=     # Assert that the following regex can be matched here:
 [0-9]* # any number of digits (and nothing but digits)
 $      # until end of string
)       # (End of lookahead)
(?:     # Match either
 .{8}   # 8 characters
|       # or
 .{11}  # 11 characters
)       # (End of alternation)
$       # End of string

这篇关于匹配特定长度 x 或 y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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