我有包含引号的文本,其中一些包含标点符号和箭头等特殊字符。例:
quotes <- c("He was thinking “my go::d I can't get out here”. So he goes “↑beep beep↑” on the horn, this bloke went “HUh HUh,”")
我想使用正则表达式只提取引号。到目前为止,我一直在玩弄包装stringr
;具体来说str_subset()
可能是相关的,但我对正则表达式太缺乏经验。 有什么帮助吗?
您可以使用基本包中的正则表达式功能来执行此操作:
quotes <- c("He was thinking “my go::d I can't get out here”. So he goes “↑beep beep↑” on the horn, this bloke went “HUh HUh,”")
pattern <- "“[^”]*”"
matches <- gregexpr(pattern, quotes)
regmatches(quotes, matches)
## [[1]]
## [1] "“my go::d I can't get out here”. So he goes “↑beep beep↑” on the horn, this bloke went “HUh HUh,”"
该函数gregexpr()
查找quotes
内出现的所有模式。然后,可以使用函数regmatches()
提取已匹配的实际文本。
该模式匹配开始和结束引号以及除结束引号之外的任何字符。排除结束引号是使用[^”]
实现的,它匹配除”
以外的任何字符。
补充两点:
- 您不能使用模式
“.*”
因为匹配是贪婪的。此模式将匹配从第一个开始到最后一个结束引用的所有内容。 - 您还可以使用 unicode 码位表示模式:
pattern <- "u201c[^u201d]*u201d"