python - 用于匹配大写字母和数字的正则表达式
问题描述
嗨,我有很多语料库,我解析它们以提取所有模式:
- 就像如何提取所有模式一样:AP70、ML71、GR55 等。
- 以及以大写字母开头的单词序列的所有模式,例如: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'
它似乎有效,但我想在解析整个“大”行时获得所有匹配项。
解决方案
试试这两个正则表达式:
(为了安全起见,它们被空白/逗号边界包围)
>>> 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,] )
推荐阅读
- redirect - nginx proxy_pass 返回重定向
- regex - 正则表达式匹配字符串中的确切字符数
- java - 如何在多个复选框之上添加 JLabel 文本?
- docker - 尝试安装但收到错误“无法通过 ssh 连接到主机:权限被拒绝(公钥,密码)”
- dask - 简单的 Dask 频率计数
- raspberry-pi - Raspberry Pi GPIO 一段时间后停止工作
- c# - 如何在 azure blob 中获取文件的 azure cdn 链接?
- android - 将回收站视图动画到外部
- python - 如何按顺序打印幂集,每对子集只有一个元素不同?
- django - Django:通过单选按钮下载文件(pdf版本或odt版本)