我正在寻找一个与PHP的 preg_match_all
函数等效的 R 语言函数。
目标:
- 搜索单个字符串(而非多个字符串的向量)以查找正则表达式模式
- 返回匹配结果矩阵
示例:
假设存在以下不带定界符的字符串。
"This is a sample string written like a paragraph. In this string two sets of information exist. Each set contains two variables. We want to extract the sets and variables within those sets. Each information set is formatted the same way. The first set is Title: Sir; Last Name: John; and the second set is Title: Mr.; Last Name: Smith."
使用类似于以下正则表达式模式:
"Title: ([^;]*?); Last Name: ([^;.]*?)"
我希望能够从上述字符串中生成以下矩阵:
[ ][,1] [,2]
[1,] Sir John
[2,] Mr. Smith
我已经成功地在远程服务器上使用
preg_match_all
函数完成了这个任务,但我要访问的文本文件相对较大(不是非常大,但上传速度比较慢)。在R中构建将节省大量时间。我已阅读有关在R中使用
grep
等的内容,但我找到的每个例子都是在向量中搜索模式,而我无法生成如上所述的矩阵。我也试过
stringr
包,但同样没有成功生成矩阵。这对我来说似乎是一项常见任务,所以我相信比我聪明的人已经找到了解决方案。
stringr::str_extract_all
(使用正则表达式"Title: ([^;]*) and Last Name: ([^;. ]*)"
) 开始,然后使用strsplit
,但是您指定的正则表达式并不完全匹配 "Title: Mr.; Last Name: Smith" ... - Ben Bolker(?i)Title: ([^;]*)(?:;| and) Last Name: ([^;.]*)
似乎符合您的要求。 - Casimir et Hippolyte