如何修剪和替换字符串

时间:2013-09-03 08:23:35

标签: regex string r

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

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

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

3 个答案:

答案 0 :(得分:6)

使用gsub

gsub(" ", "~", "    this is a string  ")
[1] "~~~~this~is~a~string~~"

此函数使用正则表达式替换(即子)字符串中所有出现的模式。

在您的情况下,您必须以特殊方式表达模式:

gsub("(^ *)|( *$)", "~~~", "    this is a string  ")
[1] "~~~this is a string~~~"

模式意味着:

  • (^ *):在字符串开始处找到一个或多个空格
  • ( *$):在字符串的结尾处找到一个或多个空格
  • `|:OR运算符

现在,您可以使用此方法解决使用新角色替换每个空间的问题:

txt <- "    this is a string  "
foo <- function(x, new="~"){
  lead <- gsub("(^ *).*", "\\1", x)
  last <- gsub(".*?( *$)", "\\1", x)
  mid  <- gsub("(^ *)|( *$)", "", x)
  paste0(
    gsub(" ", new, lead),
    mid,
    gsub(" ", new, last)
  )
}

> foo("    this is a string  ")
[1] "~~~~this is a string~~"

> foo(" And another one        ")
[1] "~And another one~~~~~~~~"

有关详情,请参阅?gsub?regexp

答案 1 :(得分:6)

这似乎是一种效率低下的方法,但也许您应该朝着gregexprregmatches的方向而不是gsub

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

答案 2 :(得分:6)

或使用更复杂的模式匹配和gsub ...

gsub("\\s(?!\\b)|(?<=\\s)\\s(?=\\b)", "~", "    this is a string  " , perl = TRUE )
#[1] "~~~~this is a string~~"

或者@ AnandaMahto的数据:

gsub("\\s(?!\\b)|(?<=\\s)\\s(?=\\b)", "~", myStrings , perl = TRUE )
#[1] "~~~~Four at the start, 2 at the end~~" 
#[2] "~~~three at the start, one at the end~"

解释

这使用正面和负面的前瞻,并查看断言背后:

  • \\s(?!\\b) - 匹配空格,\\s后面没有单词边界(?!\\b)。对于除了第一个单词之前的最后一个空格,这本身就可以工作,也就是我们自己得到的 "~~~~ this is a string~~"。所以我们需要另一种模式......

  • (?<=\\s)\\s(?=\\b) - 匹配一个空格,\\s 前面有另一个空格,(?<=\\s) 通过单词边界(?=\\b)

它是gsub所以它试图尽可能多地进行匹配。