【问题标题】:How to use positive lookbehind assertions to extract substring from string following the word "named"如何使用肯定的lookbehind断言从单词“named”之后的字符串中提取子字符串
【发布时间】:2019-03-26 01:03:33
【问题描述】:

我有一系列来自推文的熊猫文本。这些推文是关于狗的。一些推文包含狗的名字。该名称以下列方式显示。 “...blah blah blah named name。blah blah blah...” 我需要的作品前后的字符数未知。我想提取 name

我相信我需要使用积极的后向断言和正则表达式的搜索选项。我查看了 re.search 的文档以及以下 SO 问题:How to extract the substring between two markers?Regex captured groups with positive lookbehind (python),以及本教程 https://www.rexegg.com/regex-lookarounds.html。我还是觉得卡住了。

这是我目前的两个想法:

一)

tweet = 'This is a Shotokon Macadamia mix named Cheryl. Sophisticated af.'
m = re.search('(?<=named)[A-Z][a-z]+', tweet)
m.group(0)

B)

s.str.extract(^named([A-Z][a-z])\.$)

根据文档,A) 应该返回“Cheryl”,但我收到一个属性错误:AttributeError: 'NoneType' object has no attribute 'group'

B) 仅适用于系列,并非推文系列中的每个元素都包含“...命名 name”。结构体。我不确定如何将其合并到代码中,以便返回 Cheryl。

【问题讨论】:

  • 如果你使用 pandas,请使用df['col'].str.extract(r'\bnamed\s+([A-Z][a-z]*)')

标签: python regex string positive-lookahead


【解决方案1】:

Pythons 说 m'NoneType' object 因为正则表达式不匹配任何字符串,因此您无法从其结果中提取组。为了获得正确的匹配,您应该在“命名”之后添加一个空格。因此,只需尝试:

(?<=named )[A-Z][a-z]+

另见https://regex101.com/r/nZiAFN/1

【讨论】:

  • 正则表达式测试器很有帮助。
  • @a2fet this 可能会回答你,反正这是题外话
【解决方案2】:

以下正则表达式仅提取出现在命名字符串之后的名称:

m = re.search('(?<=named\s)(\w+)', tweet)

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2014-10-03
    • 2013-12-12
    • 2023-03-24
    • 2020-10-25
    • 2021-09-11
    • 2022-08-10
    • 1970-01-01
    • 2019-07-08
    相关资源
    最近更新 更多