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

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

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...