R:使用 `str_extract()` 将正则表达式匹配保存到新变量,同时从现有变量中删除正则表达式匹配

问题描述 投票:0回答:0

我想将正则表达式匹配保存到新变量,并使用一个函数从现有变量中删除正则表达式匹配。

所以在下面的例子中,我想从句子中删除“Speaker.”并将其保存到

new_variable
,同时从
sentence
.

中删除“Speaker.”

我试着用

str_extract()
来完成这个。我能够匹配所需的单词,但该单词并未从
sentence
中删除。 (这可能不是
str_extract()
的设计目的,但是
str_extract()
str_match()
之间有什么区别??)

library(stringr)

sentence <- "Speaker. I am not sure why this does not work."

for(line in sentence) {
  new_variable <- str_extract(line, "^[[:alpha:]]+\\. ") 
}

我知道我可以使用

str_replace()
从句子中删除正则表达式匹配,但如果可能的话我更愿意用一个函数来做到这一点。

library(stringr)

sentence <- "Speaker. I am not sure why this does not work."

for(line in sentence) {
  new_variable <- str_extract(line, "^[[:alpha:]]+\\. ")
  sentence <- str_replace(sentence, test, "")
}

r regex stringr
© www.soinside.com 2019 - 2024. All rights reserved.