微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式 – 如何修剪和替换字符串

string<-c("       this is a string  ")

是否可以在弦的两侧(或根据需要只是一侧)修剪掉白色空间,并用R中的所需字符替换它?字符串两侧的白色空格数不同,必须在更换时保留.

"~~~~~~~this is a string~~"

解决方法

这似乎是一种低效的方式,但也许你应该朝着gregexpr和regmatches的方向而不是gsub:

x <- "    this is a string  "
pattern <- "^ +?\\b|\\b? +$"
startstop <- gsub(" ","~",regmatches(x,gregexpr(pattern,x))[[1]])
text <- paste(regmatches(x,x),invert=TRUE)[[1]],collapse="")
paste0(startstop[1],text,startstop[2])
# [1] "~~~~this is a string~~"

而且,为了好玩,作为一个功能,以及一个“矢量化”功能

## The function
replaceEnds <- function(string) {
  pattern <- "^ +?\\b|\\b? +$"
  startstop <- gsub(" ",regmatches(string,string))[[1]])
  text <- paste(regmatches(string,string),invert = TRUE)[[1]],collapse = "")
  paste0(startstop[1],startstop[2])
}

## use Vectorize here if you want to apply over a vector
vReplaceEnds <- Vectorize(replaceEnds)

一些样本数据:

myStrings <- c("    Four at the start,2 at the end  ","   three at the start,one at the end ")

vReplaceEnds(myStrings)
#        Four at the start,2 at the end        three at the start,one at the end  
#  "~~~~Four at the start,2 at the end~~" "~~~three at the start,one at the end~"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐