【问题标题】:Matching a regex in R while excluding punctuation在排除标点符号的同时匹配 R 中的正则表达式
【发布时间】:2021-03-12 12:35:52
【问题描述】:

我有以下字符串:

x = "Mr. Mammon Moneybags is a British businessman, owner of Widgets Incorporated, the widget company, and owner of Supermarts chain store."

我想提取公司名称。显然,我想先回顾一下'owner of ',然后是一个或多个单词字符。我希望字符串在逗号和句号上被删除,但不是破折号/撇号,因为它们可能是公司名称的一部分。我也不想删减空格,因为我想捕捉“Widgets Incorporated”中的两个词,但也只捕捉“Supermarts”这个词。但在我们甚至通过指定大写单词来捕获“Supermarts”之前,我未能在“Widgets Incorporated”后面的逗号上结束捕获组。

此正则表达式仅捕获第一组的一半,但正确捕获第二组。

library(stringr)
str_extract(x, '(?<=owner of )(\w+(?!,))')
[1,] 'Widgets' [2,] 'Supermarts'

这仅部分捕获了第一组,而在第二组中过冲。

library(stringr)
str_extract(x, '(?<=owner of )(\w+\s\w+)(?!,)')
[1,] 'Widgets Incorporate' [2,] 'Supermarts chain'

我确信其中一个至少会捕获第一组。我哪里错了?

谢谢!

【问题讨论】:

  • 试试(?&lt;=owner of )[^,.]+,见demo
  • 谢谢,这比我预期的要简洁得多

标签: r regex stringr


【解决方案1】:

为了匹配每个单词必须大写的限制,您可以使用,

str_extract_all(x, '(?<=owner of\\W)([A-Z]\\w+(\\s+[A-Z]\\w+)*)')
[[1]]
[1] "Widgets Incorporated" "Supermarts"          

【讨论】:

    【解决方案2】:

    你可以使用

    stringr::str_extract(x, "(?<=owner of )[^,.]+")
    

    请参阅regex demo

    详情

    • (?&lt;=owner of ) - 紧跟在owner of + 空格前面的位置
    • [^,.]+ - 除了., 之外的一个或多个字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 2012-01-11
      • 1970-01-01
      相关资源
      最近更新 更多