匹配特定长度 x 或 y

编程入门 行业动态 更新时间:2024-10-12 20:21:38
本文介绍了匹配特定长度 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

本文发布于:2023-11-22 01:47:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615497.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:长度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!