检查字符串匹配模式

问题描述 投票:232回答:6

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

大写字母,数字(S),大写字母,数字(S)...

例如,这些将匹配:

A1B2
B10L1
C1N200J1

这些不会(“^”指向的问题)

a1B2
^
A10B
   ^
AB400
^
python regex string-matching
6个回答
385
投票
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


131
投票

一内胆: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

32
投票

请尝试以下方法:

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())

22
投票
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'

7
投票

正则表达式让这个容易...

[A-Z]将A和Z之间的精确匹配一个字符

\d+将匹配一个或多个数字

()组的事情(和返回的东西......但现在只是想他们分组)

+选择1个或多个


6
投票
  
import re

ab = re.compile("^([A-Z]{1}[0-9]{1})+$")
ab.match(string)
  

我认为,应该为大写字母,数字模式的工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.