gpt4 book ai didi

python - 用于在字符串中查找一系列大写单词的正则表达式

转载 作者:行者123 更新时间:2023-12-01 21:45:35 26 4
gpt4 key购买 nike

text = "This is a TEXT CONTAINING UPPER CASE WORDS and lower case words. This is a SECOND SENTENCE."

pattern = '[A-Z]+[A-Z]+[A-Z]*[\s]+'

re.findall(pattern, text) 给出输出 -->

['TEXT ', 'CONTAINING ', 'UPPER ', 'CASE ', 'WORDS ', 'SECOND ', 'SENTENCE ']

但是,我想要这样的输出 -->

['TEXT CONTAINING UPPER CASE WORDS', 'SECOND SENTENCE']

最佳答案

你可以使用这个正则表达式:

\b[A-Z]+(?:\s+[A-Z]+)*\b

RegEx Demo

正则表达式详细信息:

  • \b:字边界
  • [A-Z]+:匹配只包含大写字母的单词
  • (?:\s+[A-Z]+)*:匹配 1+ 个空格后跟另一个大写字母的单词。匹配该组 0 次或更多次
  • \b:单词边界

代码:

>>> s = 'This is a TEXT CONTAINING UPPER CASE WORDS and lower case words. This is a SECOND SENTENCE';
>>> print (re.findall(r'\b[A-Z]+(?:\s+[A-Z]+)*\b', s))
['TEXT CONTAINING UPPER CASE WORDS', 'SECOND SENTENCE']

关于python - 用于在字符串中查找一系列大写单词的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738190/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com