首页 > 解决方案 > 在排除标点符号的同时匹配 R 中的正则表达式

问题描述

我有以下字符串:

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'

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

谢谢!

标签: rregexstringr

解决方案


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

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

推荐阅读