我只需要替换匹配后的第一个单词。但比赛结束后所有单词都会被替换
下面的代码替换了所有单词,但我只需要删除车辆详细信息:沃尔沃
和车辆详细信息:scania_z
,而不是比赛后的所有单词
我尝试过的代码:
ad<-c("Pl. find the Vehicle Details : Volvo needs to be repaired","The vehicle number : 4570d having the Vehicle Details : scania_z should be altered")
s<-gsub("Vehicle Details :*","",ad)
s
预期结果是:
[1] "Pl. find the needs to be repaired"
[2] "The vehicle number : 4570d having the should be altered"
最佳答案
您可以使用
gsub("Vehicle Details\\s*:\\s*\\w+","",ad)
或
gsub("Vehicle Details\\s*:\\s*\\S+","",ad)
请参阅R demo
\w+
模式匹配 1+ 个字母、数字或下划线,\S+
匹配 1+ 个非空白字符。如果您想要保留的单词末尾有标点符号,则第一个是更好的选择,但如果您只想删除 :
之后的所有非空白字符,则后者是最好的选择。
关于r - gsub 匹配后的第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57722742/