如何检查字符串是否与此模式匹配?
大写字母、数字、大写字母、数字...
例如,这些将匹配:
A1B2
B10L1
C1N200J1
这些不会('^'指向问题)
a1B2
^
A10B
^
AB400
^
^([A-Z]\d+){1,}$
像这样?
B
而不是 A
。
A
和 B
都是小写字母,对吗? A10b
和 aB400
?
import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)
单行:re.match(r"pattern", string) # No need to compile
import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
... print('Yes')
...
Yes
如果需要,您可以将其评估为 bool
>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True
if
的上下文中使用 re.match
,但如果您在其他地方使用它,则必须使用 bool
?
re.match
。它只匹配字符串的开头。请查看 re.search
。
if
检查匹配项不是 None
。
re
以提高效率时,编译很有用。就错误而言,.match
会引发与 .compile
相同的错误。使用起来非常安全。
re
模块中的所有正则表达式函数都会编译和缓存模式。因此,使用编译然后匹配绝对不会比直接调用 re.match
提高效率。所有这些函数都调用内部函数 _compile
(包括 re.compile
),它对 Python 字典进行缓存。
请尝试以下方法:
import re
name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]
# Match names.
for element in name:
m = re.match("(^[A-Z]\d[A-Z]\d)", element)
if m:
print(m.groups())
import re
import sys
prog = re.compile('([A-Z]\d+)+')
while True:
line = sys.stdin.readline()
if not line: break
if prog.match(line):
print 'matched'
else:
print 'not matched'
import re
ab = re.compile("^([A-Z]{1}[0-9]{1})+$")
ab.match(string)
我相信这应该适用于大写的数字模式。
正则表达式使这很容易......
[A-Z]
将匹配 A 和 Z 之间的一个字符
\d+
将匹配一位或多位数字
()
对事物进行分组(也可以返回事物......但现在只考虑它们的分组)
+
选择 1 个或多个
如评论中所述,所有这些使用 re.match
的答案都隐式匹配字符串的开头。如果要推广到整个字符串,则需要 re.search
。
import re
pattern = re.compile("([A-Z][0-9]+)+")
# finds match anywhere in string
bool(re.search(pattern, 'aA1A1')) # True
# matches on start of string, even though pattern does not have ^ constraint
bool(re.match(pattern, 'aA1A1')) # False
信用:@LondonRob 和 @conradkleinespel 在评论中。
不定期副业成功案例分享
re.match
上的文档:If zero or more characters at the beginning of string match the regular expression pattern
。我只花了大约 30 分钟试图理解为什么我无法匹配字符串末尾的某些内容。match
似乎不可能,是吗?为此,re.search(pattern, my_string)
有效。match
时,开头有一个隐含的^
。我认为这比那个非常简单的解释要复杂一些,但我不清楚。你是对的,它确实从字符串的开头开始。search()
有意义。search()
有意义”是什么意思。它与比赛完美配合。