r - 在排除标点符号的同时匹配 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'
我确信其中一个至少会抓住第一组。我哪里错了?
谢谢!
解决方案
为了匹配每个单词必须大写的限制,您可以使用,
str_extract_all(x, '(?<=owner of\\W)([A-Z]\\w+(\\s+[A-Z]\\w+)*)')
[[1]]
[1] "Widgets Incorporated" "Supermarts"
推荐阅读
- .htaccess - .htaccess pw 受保护的文件夹刷新以访问页面?
- c - 与套接字相关的 BPF 的“输入”是什么?
- questdb - 如何在 QuestDB 数据库 Web 控制台中执行批量 sql 语句?
- javascript - Flask 和 JS 的沟通不顺利
- javascript - 覆盖多维数组
- python - 从具有平行状态的 HFSM 到 Camunda?
- python - 批量预测 Vertext AI
- asp.net-mvc - JQuery ajax 调用块 RedirectToAction
- git - fedora 上安装的 git 包在哪里?
- java - for循环中的Java removeIf条件