本文介绍了查找 5 位代码的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试根据以下条件查找模式匹配:
- 字符串长度为 5 个字符
- 字符 [0] = 字母/数字
- 字符 [1] = 字母
- 字符 [2-4] = 数字
我不明白为什么22222"适用于这个表达式?
p = r'(\w|\d)(\w)(\d){3,}'m = re.match(p, "AA012") # 按预期工作-->'AA012'm = re.match(p, "1A222") # 按预期工作-->'1A222'm = re.match(p, "22222") # 没有按预期工作!-->'22222'
我的正则表达式语法中缺少什么?
解决方案
\w
匹配字母 和 数字(以及下划线).
如果您想匹配仅个字母,请使用[a-zA-Z]
:
r'\w[a-zA-Z]\d{3,}'
匹配一个字母或数字(或下划线),然后是一个字母,然后是 3 个数字.
演示:
>>>进口重新>>>p = r'\w[a-zA-Z]\d{3,}'>>>重新匹配(p,22222")>>>重新匹配(p,AA012")<_sre.SRE_Match 对象在 0x105aca718>>>>重新匹配(p,1A222")<_sre.SRE_Match 对象在 0x105aca780>>>>重新匹配(p,_A222")<_sre.SRE_Match 对象在 0x105aca718>如果下划线有问题,请使用:
r'[a-zA-Z\d][a-zA-Z]\d{3}'
Trying to find pattern matches based on the following conditions:
- Length of string is 5 characters
- Char [0] = Letter/Number
- Char [1] = Letter
- Char [2-4] = Number
I don't understand why "22222" works for this expression?
p = r'(\w|\d)(\w)(\d){3,}'
m = re.match(p, "AA012") # Works as expected
--> 'AA012'
m = re.match(p, "1A222") # Works as expected
--> '1A222'
m = re.match(p, "22222") # Does NOT work as expected!
--> '22222'
What am I missing in my regex expression syntax?
解决方案
\w
matches letters and digits (as well as underscores).
Use [a-zA-Z]
if you want to match only letters:
r'\w[a-zA-Z]\d{3,}'
which matches a letter or digit (or an underscore), then a letter, then 3 digits.
Demo:
>>> import re
>>> p = r'\w[a-zA-Z]\d{3,}'
>>> re.match(p, "22222")
>>> re.match(p, "AA012")
<_sre.SRE_Match object at 0x105aca718>
>>> re.match(p, "1A222")
<_sre.SRE_Match object at 0x105aca780>
>>> re.match(p, "_A222")
<_sre.SRE_Match object at 0x105aca718>
If the underscore is a problem, use:
r'[a-zA-Z\d][a-zA-Z]\d{3}'
这篇关于查找 5 位代码的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!