Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex multiple pattern with singular replacement

Tags:

regex

r

stringr

I am trying to replace both "st." and "ste." with "st". Seems like the following should work but it does not:

require("stringr")
county <- c("st. landry", "ste. geneveve", "st. louis")
str_replace_all(county, c("st\\.", "ste\\."), "st")
like image 432
MikeTP Avatar asked Sep 07 '12 14:09

MikeTP


2 Answers

You can use | to mean "or"

> str_replace_all(county, "st\\.|ste\\.", "st")
[1] "st landry"   "st geneveve" "st louis"   

Or in base R

> gsub("st\\.|ste\\.", "st", county)
[1] "st landry"   "st geneveve" "st louis"  
like image 173
GSee Avatar answered Nov 19 '22 09:11

GSee


> A<-"this string,  contains a handful of,  useless:  punctuation.  Some are to escape.  Aaargh! Some might be needed,  but I want none!"
> gsub(", |: |\\. |!","",A)
[1] "this string contains a handful of useless punctuation Some are to escape Aaargh Some might be needed but I want none"
like image 2
Raberto Avatar answered Nov 19 '22 07:11

Raberto