如何使用 Python Regex 查找所有以大写字母开头的单词

问题描述

下面是从文件中查找所有大写单词并将它们添加到列表中的代码,我该如何更改它以便只将大写开头的单词添加到列表中。

import re

matches = []
regex = r"\b[A-Z]\w*"
filename = r'C:\Users\Documents\romeo.txt'
with open(filename,'r') as f:
    for line in f:
        matches += re.findall(regex,line)
print(matches)

文件

Hello,How are YOU

输出

[Hello,How]

您不应包含在输出中。

解决方法

\w 匹配大小写字母以及数字和下划线。如果只想匹配小写字母,可以这样指定:

regex = r"\b[A-Z][a-z]*\b"
text = 'Hello,How are YOU'
re.findall(pattern,text) # ['Hello','How']

查看 documentation 中的 Python 正则表达式语法以了解其他选项。