2024-09-29 08:21:33 发布
网友
如何检查字符串是否与此模式匹配?
大写字母,数字,大写字母,数字。。。
例如,它们将匹配:
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)
match
re.search()
请尝试以下操作:
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())
一行:re.match(r"pattern", string) # No need to compile
re.match(r"pattern", string) # No need to compile
import re >>> if re.match(r"hello[0-9]+", 'hello1'): ... print('Yes') ... Yes
如果需要,您可以将其评估为bool
bool
>>> bool(re.match(r"hello[0-9]+", 'hello1')) True
编辑:如注释中所述,
match
只检查字符串开头的匹配项,而re.search()
将匹配字符串中的任何模式。(另见:https://docs.python.org/library/re.html#search-vs-match)请尝试以下操作:
一行:
re.match(r"pattern", string) # No need to compile
如果需要,您可以将其评估为
bool
相关问题 更多 >
编程相关推荐