检查字符串是否匹配模式


问题内容

如何检查字符串是否与此模式匹配?

大写字母,数字,大写字母,数字…

例如,这些将匹配:

A1B2
B10L1
C1N200J1

这些不会(’^’表示问题)

a1B2
^
A10B
   ^
AB400
^

问题答案:
import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)

编辑:如注释中所述,match仅检查字符串开头的匹配项,而re.search()匹配字符串中任何位置的模式。(另请参见:https : //docs.python.org/library/re.html#search-vs-
match