简体   繁体   English

正则表达式-根据前两个字符替换单词-R

[英]regex - replace word based on first two characters - R

I'm new to regexs and trying to replace entire words based on the first two characters of a string. 我是正则表达式的新手,并尝试根据字符串的前两个字符替换整个单词。 For example, if I have a data frame called automobiles and a variable called cars, I'd like to replace Honda with Japanese. 例如,如果我有一个名为cars的数据框和一个名为cars的变量,我想用日语替换Honda。 I can get it to replace the first two characters but not the entire word. 我可以用它代替前两个字符,而不是整个单词。 Based on what I read on here, here is what I came up with, but it's not working. 根据我在这里阅读的内容,这是我想出的,但是没有用。 What am I doing wrong? 我究竟做错了什么?

automobiles$cars <- gsub(ignore.case=TRUE, "\\<^ho\\>", paste("ho", "Japanese"), automobiles$cars)

This is how you replace all strings starting with "Ho" with "Japanese: 这是用“日语”替换所有以“ Ho”开头的字符串的方法:

> cars <- c("Honda", "Audi", "Ford")

> cars
[1] "Honda" "Audi"  "Ford" 

> cars <- gsub("^Ho(.*)", "Japanese", cars, ignore.case = TRUE)

> cars
[1] "Japanese" "Audi"     "Ford"   

Your code contains some very strange stuff, so I suspect that your data/question might be more complex than that. 您的代码包含一些非常奇怪的内容,因此我怀疑您的数据/问题可能比这更复杂。 Please explain further if that is the case. 如果是这种情况,请进一步解释。

The catch is ^Ho(.*) , which selects the complete string ( (.*) is for "everything that follows") if the string starts ( ^ ) with " Ho ". 捕获是^Ho(.*) ,如果字符串以( Ho )开头( ^ ),则会选择完整的字符串( (.*)表示“紧随其后的所有内容”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM