ChatGPT解决这个技术问题 Extra ChatGPT

检查字符串是否匹配模式

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

大写字母、数字、大写字母、数字...

例如,这些将匹配:

A1B2
B10L1
C1N200J1

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

a1B2
^
A10B
   ^
AB400
^
你能解释一下为什么这是一个问题吗?
^([A-Z]\d+){1,}$ 像这样?
在您的第三个示例中,问题应该出在 B 而不是 A
也许这是问题的拼写错误。 AB 都是小写字母,对吗? A10baB400
@Burhan,问题出在A上,因为B旁边有数字而A没有

C
CrazyCasta
import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)

来自 re.match 上的文档:If zero or more characters at the beginning of string match the regular expression pattern。我只花了大约 30 分钟试图理解为什么我无法匹配字符串末尾的某些内容。 match 似乎不可能,是吗?为此,re.search(pattern, my_string) 有效。
@conradk 是的,你是对的,我认为当你使用 match 时,开头有一个隐含的 ^。我认为这比那个非常简单的解释要复杂一些,但我不清楚。你是对的,它确实从字符串的开头开始。
我编辑了您的答案,因为在这种情况下它只对 search() 有意义。
是的,但这正是提问者想要的。我不确定您所说的“仅对 search() 有意义”是什么意思。它与比赛完美配合。
需要明确的是:您可能想检查 pattern.match 是否返回一些东西;幸运的是“None”是真实的,所以你可以做“if pattern.match:”
n
nehem

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

这很奇怪。为什么您可以在 if 的上下文中使用 re.match,但如果您在其他地方使用它,则必须使用 bool
小心使用 re.match。它只匹配字符串的开头。请查看 re.search
@LondonRob 可能是因为 if 检查匹配项不是 None
@SuhFangmbeng 当在多个地方使用相同的 re 以提高效率时,编译很有用。就错误而言,.match 会引发与 .compile 相同的错误。使用起来非常安全。
@nehem 实际上 re 模块中的所有正则表达式函数都会编译和缓存模式。因此,使用编译然后匹配绝对不会比直接调用 re.match 提高效率。所有这些函数都调用内部函数 _compile(包括 re.compile),它对 Python 字典进行缓存。
E
Edd

请尝试以下方法:

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

这是唯一返回获取组所需的匹配的情况。我认为的最佳答案。
其他答案中的最佳答案
M
Marc Cohen
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'

K
Kneel-Before-ZOD

import re

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

我相信这应该适用于大写的数字模式。


J
Joran Beasley

正则表达式使这很容易......

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

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

() 对事物进行分组(也可以返回事物......但现在只考虑它们的分组)

+ 选择 1 个或多个


c
crypdick

如评论中所述,所有这些使用 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

信用:@LondonRob 和 @conradkleinespel 在评论中。