【问题标题】:Find consecutive capitalized words in a string, including apostrophes在字符串中查找连续的大写单词,包括撇号
【发布时间】:2020-07-23 18:55:44
【问题描述】:

我正在使用正则表达式来查找所有连续单词的实例,这些单词都是大写的,并且其中一些连续单词包含撇号,即(“The Mother-Daughter bakery, Molly's Munchies,成立于 2009 年”)。我已经写了几行代码来做到这一点:

string = "The mother-daughter bakery, Molly’s Munchies, was founded in 2009"
test = re.findall("([A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+)", string)
print(test)

问题是我无法打印结果('Molly's Munchies')

我的输出是:

('[]')

期望的输出:

("Molly's Munchies")

任何帮助表示赞赏,谢谢!

【问题讨论】:

  • re.findall(r"(?!^)\b[A-Z][a-z]+(?:'s?)?(?:\s+[A-Z][a-z]+(?:'s?)?)+", string)?

标签: python regex findall apostrophe capitalization


【解决方案1】:

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

r"\b[A-Z][a-z'’]*(?:\s+[A-Z][a-z'’]*)+"

RegEx Demo

正则表达式详细信息:

  • \b:字匹配
  • [A-Z]:匹配大写字母
  • [a-z'’]*:匹配0个或多个包含小写字母或'的字符
  • (?:\s+[A-Z][a-z'’]*)+ 匹配 1 个或多个这样的大写字母单词

【讨论】:

  • 嗨 Anubhava 感谢您的评论,我意识到我在给出的示例字符串中犯了一个小错误。相反,我的字符串是““The Cow goes moo and the Dog's Name, is orange”,在第二个大写单词(Name)之后没有空格。如何在正则表达式代码中做出这个规定?谢谢
  • 即使Name 后面没有空格,它仍然会匹配Dog's Name。也可以查看演示:regex101.com/r/NYhskl/2
  • 有趣,我看到逗号你的代码仍然是正确的,但我很抱歉造成混淆,我只是想创建一个类似的例子,我用于我的项目的真实字符串是“母女面包店Molly's Munchies,成立于2009年”。我曾尝试创建一个与此类似的示例,并认为逗号可能是问题所在。但是代码不适用于这个字符串,有什么想法吗?
  • 这是因为你的撇号字符是 而不是' 所以你可以使用:regex101.com/r/NYhskl/3
  • 感谢您对帮助的承诺,我很感激。
【解决方案2】:

您需要在定义“单词”的两个地方添加它。您只在一处添加了它。

string = "The Cow goes moo, and the Dog's Name is orange"
# e.g. both                here                    and here
#                           v                           v
print(re.findall("([A-Z][a-z']+(?=\s[A-Z])(?:\s[A-Z][a-z']+)+)", string))
['The Cow', "Dog's Name"]

【讨论】:

  • 嗨 Cireo,您和 Anubhava 都很快,感谢您的评论,我意识到我在给出的示例字符串中犯了一个小错误。相反,我的字符串是""The Cow goes moo and the Dog's Name, is orange",其中第二个大写单词 (Name) 之后没有空格。如何在正则表达式代码中做出这个规定?谢谢
猜你喜欢
  • 1970-01-01
  • 2014-11-28
  • 2014-08-20
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 2016-07-27
  • 2016-08-18
  • 1970-01-01
相关资源
最近更新 更多