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

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

例如,这些将匹配:

A1B2
B10L1
C1N200J1

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

a1B2
^
A10B
   ^
AB400
^

当前回答

re.match(r"pattern", string) #不需要编译

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

如果需要,可以将其计算为bool值

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

其他回答

正如注释中所述,所有这些答案都使用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

如果你需要完整的字符串来精确匹配正则表达式,请参阅@Ali Sajjad使用re.fullmatch的回答

来源:@LondonRob和@conradkleinespel在评论中。

re.match(r"pattern", string) #不需要编译

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

如果需要,可以将其计算为bool值

>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True
import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)
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'

小心!(也许你想检查FULL字符串是否匹配)

如果你想匹配完整的字符串,re.match(…)将不起作用。

例如;

Re.match ("[a-z]+", "abcdef")✅会给出一个匹配 但是!Re.match ("[a-z]+", "abcdef 12345")✅也会给出一个匹配,因为字符串中有一个匹配的部分(也许你不希望当你检查整个字符串是否有效时)

解决方案

使用re.fullmatch(…)。仅当

if re.fullmatch("[a-z]+", my_string):
    print("Yes")

例子

fullmatch(之王”[a - z] +”、“abcdef)✅Yes 国王,fullmatch(“[a - z] +”,“abcdef 12345”)❌不

一行代码:bool(re。fullmatch(“[a - z] +”,my_string))