简体   繁体   中英

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. 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:

> 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 ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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