代码之家  ›  专栏  ›  技术社区  ›  dasf

r:regex捕获给定字符后的所有实例

  •  1
  • dasf  · 技术社区  · 6 年前

    给定字符串 ab cd ; ef gh ij ,如何删除第一个空格之后的所有空格 ; ,即 ab cd ; efghij ?我试着用 \K 但不能完全发挥作用。

    test = 'ab cd  ; ef  gh ij'
    gsub('(?<=; )[^ ]+\\K +','',test,perl=T)
    # "ab cd  ; efgh ij"
    
    0 回复  |  直到 6 年前
        1
  •  4
  •   G. Grothendieck    6 年前

    1)GSBFN 使用 gsubfn 在gsubfn包中,这里有一个只使用简单正则表达式的单行代码。它将捕获组输入到指定的函数中(用公式表示法表示),并用函数的输出替换匹配。

    library(gsubfn)
    
    gsubfn("; (.*)", ~ paste(";", gsub(" ", "", x)), test)
    ## [1] "ab cd  ; efghij"
    

    2)GSUB 这使用一个模式,该模式由空格组成,空格前不紧跟分号,字符串其余部分后面不紧跟分号。

    gsub("(?<!;) (?!.*; )", "", test, perl = TRUE)
    ## [1] "ab cd  ; efghij"
    

    3)regexpr/子字符串 找到分号的位置,然后使用 substring 把它分成两部分用 gsub 最后把它粘在一起。

    ix <- regexpr(";", test)
    paste(substring(test, 1, ix), gsub(" ", "", substring(test, ix + 2)))
    ## [1] "ab cd  ; efghij"
    

    4)读取表 这与(3)类似,但使用 read.table 将输入分为两个字段。

    with(read.table(text = test, sep = ";", as.is = TRUE), paste0(V1, "; ", gsub(" ", "", V2)))
    ## [1] "ab cd  ; efghij"
    
        2
  •  3
  •   Andrew    6 年前

    我确信有一个regex解决方案(希望有人发布),但这里有一个非regex解决方案,它依赖于分号的一致性。如果有多个分隔符,可以调整它。希望有帮助!

    > # Split the string on the semi-colon (assumes semi-colon is consistent)
    > split <- strsplit(c("ab cd  ; ef  gh ij", "abcd e f ; gh ij k"), ";")
    > 
    > # Extract elements separately
    > pre_semicolon <- sapply(split, `[`, 1)
    > post_semicolon <- sapply(split, `[`, 2)
    > 
    > # Remove all spaces from everything after the semi-colon
    > post_semicolon <- gsub("[[:space:]]", "", post_semicolon)
    > 
    > # Paste them back together with a semi-colon and a space
    > paste(pre_semicolon, post_semicolon, sep = "; ")
    [1] "ab cd  ; efghij"  "abcd e f ; ghijk"