Python正则表达式:匹配所有连续的大写单词

时间:2013-12-17 20:36:16

标签: python regex python-2.7 python-3.x capitalize

简短的问题:

我有一个字符串:

title="Announcing Elasticsearch.js For Node.js And The Browser"

我想找到每个单词都被正确大写的所有单词对。

所以,预期的输出应该是:

['Announcing Elasticsearch.js', 'Elasticsearch.js For', 'For Node.js', 'Node.js And', 'And The', 'The Browser']

我现在拥有的是:

'[A-Z][a-z]+[\s-][A-Z][a-z.]*'

这给了我输出:

['Announcing Elasticsearch.js', 'For Node.js', 'And The']

如何更改正则表达式以提供所需的输出?

3 个答案:

答案 0 :(得分:2)

您可以使用:

#!/usr/bin/python
import re

title="Announcing Elasticsearch.js For Node.js And The Browser TEst"
pattern = r'(?=((?<![A-Za-z.])[A-Z][a-z.]*[\s-][A-Z][a-z.]*))'

print re.findall(pattern, title)

“正常”模式无法匹配重叠的子串,所有字符都是一次性建立的。但是,前瞻(?=..)(即“后跟”)只是一个检查并且不匹配。它可以多次解析字符串。因此,如果将捕获组放在前瞻中,则可以获得重叠的子串。

答案 1 :(得分:0)

这可能是一种更有效的方法,但您可以使用这样的正则表达式:

(\b[A-Z][a-z.-]+\b)

然后迭代捕获组,如此使用此正则表达式进行测试:(^[A-Z][a-z.-]+$)以确保匹配的组(当前)与匹配的组(下一个)匹配。

工作示例:

import re

title = "Announcing Elasticsearch.js For Node.js And The Browser"
matchlist = []
m = re.findall(r"(\b[A-Z][a-z.-]+\b)", title)
i = 1
if m:
    for i in range(len(m)):
        if re.match(r"(^[A-Z][a-z.-]+$)", m[i - 1]) and re.match(r"(^[A-Z][a-z.-]+$)", m[i]):
            matchlist.append([m[i - 1], m[i]])

print matchlist

<强>输出:

[
    ['Browser', 'Announcing'], 
    ['Announcing', 'Elasticsearch.js'], 
    ['Elasticsearch.js', 'For'], 
    ['For', 'Node.js'], 
    ['Node.js', 'And'], 
    ['And', 'The'], 
    ['The', 'Browser']
]

答案 2 :(得分:0)

如果您目前的Python代码是

title="Announcing Elasticsearch.js For Node.js And The Browser"
results = re.findall("[A-Z][a-z]+[\s-][A-Z][a-z.]*", title)

然后你的程序正在跳过奇数对。一个简单的解决方案是在跳过第一个单词之后研究模式:

m = re.match("[A-Z][a-z]+[\s-]", title)
title_without_first_word = title[m.end():]
results2 = re.findall("[A-Z][a-z]+[\s-][A-Z][a-z.]*", title_without_first_word)

现在只需将结果和result2结合起来。

相关问题