正则表达式匹配连续的 n(字母数字) [英] Regex to match consecutive n (alpha numeric)
问题描述
我正在尝试匹配字符串中连续的 n 个(字母数字)字符.
I am trying to match consecutive n(alpha numeric) characters in a string.
其中 n = 3
i7g172w2n YES (it has 3 consecutive number)
adab172cd NO (it has 4 consecutive alpha even though it has 3 consecutive number)
aaa172afa YES (it has 3 consecutive number and 3 consecutive alpha)
ab21cd172 YES
abc21a3d3 YES
有人能帮我吗.
这是我的正则表达式:(\D(\d{3})\D)|\d([a-z]{3})\d
不起作用.
Here is my regex : (\D(\d{3})\D)|\d([a-z]{3})\d
not working.
推荐答案
尝试使用以下正则表达式.
Try with following regex.
正则表达式: ^(?:(?:\d{0,3}[az]{1,3}\d{1,3})+|(?:[az]{0,3}\d{1,3}[az]{1,3})+)$
说明:基本上我所做的是匹配以下模式.
Explanation: Basically what I have done is matched following patterns.
(?:\d{0,3}[a-z]{1,3}\d{1,3})+
- (
0-3 Digit
1-3 Alphabets
1-3 Digits
)<-
超过一次.
- (
0-3 Digit
1-3 Alphabets
1-3 Digits
)<-
More than one time.
(?:[a-z]{0,3}\d{1,3}[a-z]{1,3})+
- (
0-3 Alphabets
1-3 Digits
1-3 Alphabets
)<-
超过一次.
- (
0-3 Alphabets
1-3 Digits
1-3 Alphabets
)<-
More than one time.
因为两者是交替的,因此这两个模式中的任何一个都会匹配.
Since both are in alternation, hence either of these pattern will be matched.
对于字符串 i7g172w2n
子匹配将是 i
-7
-g
-172
-w
-2
-n
.符合规范.
For string i7g172w2n
sub matches will be i
-7
-g
-172
-w
-2
-n
. Which fits into the specifications.
对于字符串 adsb172cd
子匹配将是 adsb
-172
-cd
.由于 adsb
超过长度 3.因此不会匹配.
For string adsb172cd
sub matches will be adsb
-172
-cd
. Since adsb
exceeds length 3. Hence won't be matched.
与abc2p7373
类似,7373
超过长度3.
这篇关于正则表达式匹配连续的 n(字母数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!