Stringr str_替换_所有未命中重复项
我对stringr::str_replace_all函数有问题。我试图用insuredvehicle替换所有iv实例,但该函数似乎只包含第一个术语Stringr str_替换_所有未命中重复项,r,regex,str-replace,stringr,R,Regex,Str Replace,Stringr,我对stringr::str_replace_all函数有问题。我试图用insuredvehicle替换所有iv实例,但该函数似乎只包含第一个术语 temp_data <- data.table(text = 'the driver of the 1st vehicle hit the iv iv at a stop') temp_data[, new_text := stringr::str_replace_all(pattern = ' iv ', replacement = ' in
temp_data <- data.table(text = 'the driver of the 1st vehicle hit the iv iv at a stop')
temp_data[, new_text := stringr::str_replace_all(pattern = ' iv ', replacement = ' insuredvehicle ', string = text)]
temp_data如果在正则表达式中包含单词边界,那么是否可以删除替换中的空格?当您只需要一个与模式匹配的完整单词,而不需要部分单词,同时避免这些空白问题时,这是非常理想的。
\\b
似乎起到了作用
temp_data[, new_text := stringr::str_replace_all(pattern = '\\biv\\b', replacement = 'insuredvehicle', string = text)]
new_text
1: the driver of the 1st vehicle hit the insuredvehicle insuredvehicle at a stop
您可以使用lookarounds:
temp\u data[,new\u text:=stringr::str\u replace\u all(模式=”(?使用gsub
:
gsub("\\biv\\b", "insuredvehicle", temp_data$text)
[1] "the driver of the 1st vehicle hit the uninsuredvehicle uninsuredvehicle at a stop"
使用空间边界:
temp\u数据
看
解释
--------------------------------------------------------------------------------
(?这非常简单,并且与我正在运行的其他代码无缝配合。这似乎是一个比在模式周围使用空格更好的解决方案。这使它更难阅读,但可以完成工作!谢谢!我非常感谢您的解释!这对了解正则表达式的情况非常有帮助。我喜欢这个解决方案,因为它使搜索模式相当容易看到。