【问题标题】:A Regex to remove digits except for words starting with #一个正则表达式,用于删除除以 # 开头的单词之外的数字
【发布时间】:2019-12-07 10:32:06
【问题描述】:

我有一些字符串可以包含字母、数字和“#”符号。

我想删除除以“#”开头的单词以外的数字

这是一个例子:

"table9 dolv5e #10n #dec10 #nov8e 23 hello"

预期的输出是:

"table dolve #10n #dec10 #nov8e  hello"

如何使用 regex、stringr 或 gsub 做到这一点?

【问题讨论】:

    标签: r regex gsub stringr


    【解决方案1】:

    capturing 想要的,然后用空的(未捕获的)替换不需要的。

    gsub("(#\\S+)|\\d+","\\1",x)
    

    See demo at regex101R demo at tio.run(我对 R 没有经验)

    我的回答是假设#foo bar #baz2 之间总是有空格。如果您有 #foo1,bar2:#baz3 4use \w(单词字符)之类的东西,而不是 \S(非空格)。

    【讨论】:

      【解决方案2】:

      您可以在空格上拆分字符串,如果标记不以“#”开头,则从标记中删除数字并粘贴回来:

      x <- "table9 dolv5e #10n #dec10 #nov8e 23 hello"
      y <- unlist(strsplit(x, ' '))
      paste(ifelse(startsWith(y, '#'), y, sub('\\d+', '', y)), collapse = ' ')
      # output 
      [1] "table dolve #10n #dec10 #nov8e  hello"
      

      【讨论】:

        【解决方案3】:

        你用gsub去掉数字,例如:

        gsub("[0-9]","","table9")
        "table"
        

        我们可以使用 strsplit 拆分您的字符串:

        STRING = "table9 dolv5e #10n #dec10 #nov8e 23 hello"
        strsplit(STRING," ")
        [[1]]
        [1] "table9" "dolv5e" "#10n"   "#dec10" "#nov8e" "23"     "hello"
        

        我们只需要使用 gsub 遍历 STRING,仅将其应用于没有“#”的元素

        STRING = unlist(strsplit(STRING," "))
        no_hex = !grepl("#",STRING)
        STRING[no_hex] = gsub("[0-9]","",STRING[no_hex])
        paste(STRING,collapse=" ")
        [1] "table dolve #10n #dec10 #nov8e  hello"
        

        【讨论】:

          【解决方案4】:

          基础 R 解决方案:

          unlisted_strings <- unlist(strsplit(X, "\\s+"))
          
          Y <- paste0(na.omit(ifelse(grepl("[#]", unlisted_strings),
          
                                     unlisted_strings,
          
                                     gsub("\\d+", "", unlisted_strings))), collapse = " ")
          
          Y 
          

          数据:

          X <- as.character("table9 dolv5e #10n #dec10 #nov8e 23 hello")
          

          【讨论】:

          • 这没有给出想要的输出。
          【解决方案5】:
          INPUT = "table9 dolv5e #10n #dec10 #nov8e 23 hello";
          OUTPUT = INPUT.match(/[^#\d]+(#\w+|[A-Za-Z]+\w*)/gi).join('');
          

          您可以删除标志i,因为它不区分大小写

          使用此模式:[^#\d]+(#\w+|[A-Za-Z]+\w*)

          [^#\d]+ = 以无# 和数字开头的字符 #\w+ = find # 后跟数字或字母 [A-Za-z]+\w* = 查找字母后跟字母和/或数字 ^ | 您可以使用\D+\S* 更改此设置= 查找任何字符,而不仅仅是在第一个是字母时,而不仅仅是在字母和/或数字之后。 我不是\w+\w*,因为\w等于=[\w\d]

          我尝试了 JavaScript 中的代码,它可以工作。 如果你想匹配的不仅仅是字母,你可以使用代码

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-12-02
            • 2019-01-21
            • 1970-01-01
            • 2020-09-03
            相关资源
            最近更新 更多