问题
I am trying to match consecutive n(alpha numeric) characters in a string.
Where 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
Can some one help me.
Here is my regex : (\D(\d{3})\D)|\d([a-z]{3})\d
not working.
回答1:
Try with following regex.
Regex: ^(?:(?:\d{0,3}[a-z]{1,3}\d{1,3})+|(?:[a-z]{0,3}\d{1,3}[a-z]{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
)<-
More than one time.
- (
(?:[a-z]{0,3}\d{1,3}[a-z]{1,3})+
- (
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.
For string i7g172w2n
sub matches will be i
-7
-g
-172
-w
-2
-n
. Which fits into the specifications.
For string adsb172cd
sub matches will be adsb
-172
-cd
. Since adsb
exceeds length 3. Hence won't be matched.
Similarly for abc2p7373
, 7373
exceeds length 3.
Regex101 Demo
回答2:
While there almost certainly is a pure-regex solution to this problem, it's going to be an incomprehensible mess involving lookahead assertions. If you do some of the work in code instead of regex, the problem becomes much more straightforward (Python shown):
import re
def consecutive(s, n):
matches = re.findall("\d+|[a-z]+", s)
longest = max(map(len, matches))
return longest == n
for test in ["i7g172w2n", "adab172cd", "aaa172afa", "ab21cd172", "abc21a3d3", "12a3b3b3b"]:
print test, consecutive(test, 3)
Basically, it verifies that the longest consecutive sequence of digits or letters is exactly the required number, no more nor less. Output:
i7g172w2n True
adab172cd False
aaa172afa True
ab21cd172 True
abc21a3d3 True
12a3b3b3b False
来源:https://stackoverflow.com/questions/44170109/regex-to-match-consecutive-n-alpha-numeric