正则表达式多重模式与单数替换

时间:2012-09-07 14:58:29

标签: regex r stringr

我正在尝试更换两个" st。"和" ste。"与" st"。似乎以下情况应该有效,但事实并非如此:

require("stringr")
county <- c("st. landry", "ste. geneveve", "st. louis")
str_replace_all(county, c("st\\.", "ste\\."), "st")

2 个答案:

答案 0 :(得分:42)

您可以使用|表示“或”

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

或在基地R

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

答案 1 :(得分:0)

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