首页 > 解决方案 > 用于匹配大写字母和数字的正则表达式

问题描述

嗨,我有很多语料库,我解析它们以提取所有模式:

  1. 就像如何提取所有模式一样:AP70、ML71、GR55 等。
  2. 以及以大写字母开头的单词序列的所有模式,例如:Hello Little Monkey、How Are You 等。

对于第一种情况,我做了这个正则表达式并且没有得到所有匹配项:

>>> p = re.compile("[A-Z]+[0-9]+")
>>> res = p.search("aze azeaz GR55 AP1 PM89")
>>> res
<re.Match object; span=(10, 14), match='GR55'>

对于第二个:

>>> s = re.compile("[A-Z]+[a-z]+\s[A-Z]+[a-z]+\s[A-Z]+[a-z]+")
>>> resu = s.search("this is a test string, Hello Little Monkey, How Are You ?")
>>> resu
<re.Match object; span=(23, 42), match='Hello Little Monkey'>
>>> resu.group()
'Hello Little Monkey'

它似乎有效,但我想在解析整个“大”行时获得所有匹配项。

标签: pythonregexregex-lookaroundsregex-groupregex-greedy

解决方案


试试这两个正则表达式:

(为了安全起见,它们被空白/逗号边界包围)


>>> import re
>>> teststr = "aze azeaz GR55 AP1 PM89"
>>> res = re.findall(r"(?<![^\s,])[A-Z]+[0-9]+(?![^\s,])", teststr)
>>> print(res)
['GR55', 'AP1', 'PM89']
>>>

可读的正则表达式

 (?<! [^\s,] )
 [A-Z]+ [0-9]+ 
 (?! [^\s,] )

>>> import re
>>> teststr = "this is a test string, ,Hello Little Monkey, How Are You ?"
>>> res = re.findall(r"(?<![^\s,])[A-Z]+[a-z]+(?:\s[A-Z]+[a-z]+){1,}(?![^\s,])", teststr)
>>> print(res)
['Hello Little Monkey', 'How Are You']
>>>

可读的正则表达式

 (?<! [^\s,] )
 [A-Z]+ [a-z]+ 
 (?: \s [A-Z]+ [a-z]+ ){1,}
 (?! [^\s,] )

推荐阅读