检查字符串是否与模式匹配

2024-09-29 08:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

大写字母,数字,大写字母,数字。。。

例如,它们将匹配:

A1B2
B10L1
C1N200J1

这些不会('^'指向问题)

a1B2
^
A10B
   ^
AB400
^

Tags: 字符串数字大写字母指向a1b2a10bc1n200j1ab400
3条回答
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

请尝试以下操作:

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

import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
...     print('Yes')
... 
Yes

如果需要,您可以将其评估为bool

>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True

相关问题 更多 >