在Python中使用正则表达式捕获所有连续的全大写单词?

2024-01-02

我正在尝试使用Python中的正则表达式来匹配所有连续的大写单词/短语。鉴于以下情况:

    text = "The following words are ALL CAPS. The following word is in CAPS."

代码将返回:

    ALL CAPS, CAPS

我目前正在使用:

    matches = re.findall('[A-Z\s]+', text, re.DOTALL)

但这返回:

    ['T', ' ', ' ', ' ', ' ALL CAPS', ' T', ' ', ' ', ' ', ' ', ' CAPS']

我显然不想要标点符号或“T”。我只想返回连续的单词或仅包含所有大写字母的单个单词。

Thanks


这个可以完成以下工作:

import re
text = "tHE following words aRe aLL CaPS. ThE following word Is in CAPS."
matches = re.findall(r"(\b(?:[A-Z]+[a-z]?[A-Z]*|[A-Z]*[a-z]?[A-Z]+)\b(?:\s+(?:[A-Z]+[a-z]?[A-Z]*|[A-Z]*[a-z]?[A-Z]+)\b)*)",text)
print matches

Output:

['tHE', 'aLL CaPS', 'ThE', 'Is', 'CAPS']

解释:

(           : start group 1
  \b        : word boundary
  (?:       : start non capture group
    [A-Z]+  : 1 or more capitals
    [a-z]?  : 0 or 1 small letter
    [A-Z]*  : 0 or more capitals
   |        : OR
    [A-Z]*  : 0 or more capitals
    [a-z]?  : 0 or 1 small letter
    [A-Z]+  : 1 or more capitals
  )         : end group
  \b        : word boundary
  (?:       : non capture group
    \s+     : 1 or more spaces
    (?:[A-Z]+[a-z]?[A-Z]*|[A-Z]*[a-z]?[A-Z]+) : same as above
    \b      : word boundary
  )*        : 0 or more time the non capture group
)           : end group 1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Python中使用正则表达式捕获所有连续的全大写单词? 的相关文章

随机推荐