在Python中使用正则表达式查找首字母缩写词 [英] Finding Acronyms Using Regex In Python

查看:809
本文介绍了在Python中使用正则表达式查找首字母缩写词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中使用正则表达式来匹配以句点分隔的首字母缩写词.我有以下代码:

I'm trying to use regex in Python to match acronyms separated by periods. I have the following code:

import re
test_string = "U.S.A."
pattern = r'([A-Z]\.)+'
print re.findall(pattern, test_string)

其结果是:

['A.']

我很困惑为什么这是结果.我知道+是贪婪的,但是为什么是[A-Z] \的第一个出现.被忽略了吗?

I'm confused as to why this is the result. I know + is greedy, but why is are the first occurrences of [A-Z]\. ignored?

推荐答案

正则表达式中的(...)创建一个组.我建议更改为:

The (...) in regex creates a group. I suggest changing to:

pattern = r'(?:[A-Z]\.)+'

这篇关于在Python中使用正则表达式查找首字母缩写词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆