如何使用 Python 正则表达式查找以大写字母开头的所有单词

How to find all words that start with an uppercase letter using 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 正则表达式语法以了解其他选项。