【问题标题】:Regex to find words starting with capital letters not at beginning of sentence正则表达式查找以大写字母开头的单词而不是句子的开头
【发布时间】:2018-08-29 12:42:34
【问题描述】:

我已经设法找到以大写字母开头的单词,但无法找出一个正则表达式来过滤掉从句子开头开始的单词。

每个句子都以句号和空格结尾。

  • Test_string = This is a Test sentence. The sentence is Supposed to Ignore the Words at the beginning of the Sentence.

  • 所需输出 = ['Test', 'Supposed', 'Ignore', 'Words', 'Sentence']

我正在使用 Python 进行编码。 如果有人可以帮助我使用正则表达式会很高兴:)

【问题讨论】:

  • 顺便欢迎来到 Stack Overflow。你的问题得到了几票反对,因为你没有表现出你在解决问题方面的努力,也许期望的输出不是很清楚。以后提出问题时请考虑这一点。

标签: python regex


【解决方案1】:

您可以使用以下表达式:

(?<!^)(?<!\. )[A-Z][a-z]+

正则表达式演示here.


import re
mystr="This is a Test sentence. The sentence is Supposed to Ignore the Words at the beginning of the Sentence."

print(re.findall(r'(?<!^)(?<!\. )[A-Z][a-z]+',mystr))

打印:

['Test', 'Supposed', 'Ignore', 'Words', 'Sentence']

【讨论】:

  • 非常感谢。这已经困扰了我很长时间了。
  • 没问题,不客气。如果它解决了问题,请考虑接受答案。请参阅here 如何操作。
  • 尽管如果句子中间的大写单词从新行开始(例如"This is a\n" + "Test sentence."),那么正则表达式将无法捕获该单词。不过,我不确定这是否会成为 OP 的问题。
【解决方案2】:

一个非常基本的选项。请参阅here 了解说明。

[^.]\s([A-Z]\w+)

import re
s = 'This is a Test sentence. The sentence is Supposed to Ignore the Words at the beginning of the Sentence, And others.'
re.findall(r'[^.]\s([A-Z]\w+)', s)

输出

['Test', 'Supposed', 'Ignore', 'Words', 'Sentence', 'And']

【讨论】:

  • 字符集中的第二个^ 是干什么用的?
  • 这不是它的工作原理。元字符在字符集中失去了意义。
  • 感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
  • 2017-07-09
  • 2011-07-23
  • 1970-01-01
相关资源
最近更新 更多