问题:检查字符串是否匹配模式

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

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

例如,这些将匹配:

A1B2
B10L1
C1N200J1

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

a1B2
^
A10B
   ^
AB400
^

How do I check if a string matches this pattern?

Uppercase letter, number(s), uppercase letter, number(s)…

Example, These would match:

A1B2
B10L1
C1N200J1

These wouldn’t (‘^’ points to problem)

a1B2
^
A10B
   ^
AB400
^

回答 0

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
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)

Edit: As noted in the comments match checks only for matches at the beginning of the string while re.search() will match a pattern anywhere in string. (See also: https://docs.python.org/library/re.html#search-vs-match)


回答 1

单线: 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

One-liner: re.match(r"pattern", string) # No need to compile

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

You can evalute it as bool if needed

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

回答 2

请尝试以下操作:

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

Please try the following:

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

回答 3

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'
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'

回答 4

正则表达式使这变得容易…

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

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

() 对事物进行分组(并且还返回事物…但是现在仅考虑将它们分组)

+ 选择1个或更多

regular expressions make this easy …

[A-Z] will match exactly one character between A and Z

\d+ will match one or more digits

() group things (and also return things… but for now just think of them grouping)

+ selects 1 or more


回答 5

  
import re

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


我认为这应该适用于大写的数字模式。


import re

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


I believe that should work for an uppercase, number pattern.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。