在排除标点符号的同时匹配 R 中的正则表达式
Matching a regex in R while excluding punctuation
我有以下字符串:
x = "Mr. Mammon Moneybags is a British businessman, owner of Widgets Incorporated, the widget company, and owner of Supermarts chain store."
我想提取公司名称。显然,我想从回顾 'owner of '
开始,然后是一个或多个单词字符。我希望字符串在逗号和句号处被截断,但在 dashes/apostrophes 处不截断,因为它们可能是公司名称的一部分。我也不想删掉空格,因为我想捕捉“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'
我确信其中一个至少会捕获第一组。我哪里错了?
谢谢!
为了匹配每个单词必须大写的限制,您可以使用,
str_extract_all(x, '(?<=owner of\W)([A-Z]\w+(\s+[A-Z]\w+)*)')
[[1]]
[1] "Widgets Incorporated" "Supermarts"
你可以使用
stringr::str_extract(x, "(?<=owner of )[^,.]+")
参见regex demo。
详情:
(?<=owner of )
- 紧接 owner of
+ space 的位置
[^,.]+
- .
和 ,
. 以外的一个或多个字符
我有以下字符串:
x = "Mr. Mammon Moneybags is a British businessman, owner of Widgets Incorporated, the widget company, and owner of Supermarts chain store."
我想提取公司名称。显然,我想从回顾 'owner of '
开始,然后是一个或多个单词字符。我希望字符串在逗号和句号处被截断,但在 dashes/apostrophes 处不截断,因为它们可能是公司名称的一部分。我也不想删掉空格,因为我想捕捉“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'
我确信其中一个至少会捕获第一组。我哪里错了?
谢谢!
为了匹配每个单词必须大写的限制,您可以使用,
str_extract_all(x, '(?<=owner of\W)([A-Z]\w+(\s+[A-Z]\w+)*)')
[[1]]
[1] "Widgets Incorporated" "Supermarts"
你可以使用
stringr::str_extract(x, "(?<=owner of )[^,.]+")
参见regex demo。
详情:
(?<=owner of )
- 紧接owner of
+ space 的位置
[^,.]+
-.
和,
. 以外的一个或多个字符