foo(" And another one ") -6ren">
gpt4 book ai didi

regex - 如何修剪和替换字符串

转载 作者:行者123 更新时间:2023-12-04 16:29:17 26 4
gpt4 key购买 nike

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

是否可以在 R 中修剪字符串两侧(或仅根据需要仅一侧)的空白并将其替换为所需的字符,例如这个?字符串每一侧的空格数不同,必须在替换时保留。
"~~~~~~~this is a string~~"

最佳答案

使用 gsub :

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

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

在您的情况下,您必须以特殊方式表达模式:
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 .

    关于regex - 如何修剪和替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18587399/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com