加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:06:34 所属栏目:百科 来源:网络整理
导读:string-c(" this is a string ") 是否可以在弦的两侧(或根据需要只是一侧)修剪掉白色空间,并用R中的所需字符替换它?字符串两侧的白色空格数不同,必须在更换时保留. "~~~~~~~this is a string~~" 解决方法 这似乎是一种低效的方式,但也许你应该朝着gregexpr
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~"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读