【问题标题】:R: regex to capture all instances after a given characterR:正则表达式捕获给定字符之后的所有实例
【发布时间】:2019-07-24 15:39:06
【问题描述】:

给定字符串ab cd ; ef gh ij,如何删除; 之后的第一个空格之后的所有空格,即ab cd ; efghij?我尝试使用\K,但无法完全正常工作。

test = 'ab cd  ; ef  gh ij'
gsub('(?<=; )[^ ]+\\K +','',test,perl=T)
# "ab cd  ; efgh ij"

【问题讨论】:

    标签: r regex pcre backreference


    【解决方案1】:

    我确信有一个正则表达式解决方案(我希望有人发布),但这是一个依赖分号一致的非正则表达式解决方案。如果有多个分隔符,您可以对其进行调整。希望对您有所帮助!

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

    【讨论】:

    • 是的,这就是我最终所做的。但如果只是为了它的狂妄自大,正则表达式解决方案会很棒。
    【解决方案2】:

    1) gsubfn 使用 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 这会找到分号的位置,然后使用substring 将其分成两部分并用gsub 替换空格,最后将其粘贴在一起。

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

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

    with(read.table(text = test, sep = ";", as.is = TRUE), paste0(V1, "; ", gsub(" ", "", V2)))
    ## [1] "ab cd  ; efghij"
    

    【讨论】:

    • 太棒了。谢谢!
    猜你喜欢
    • 2015-08-04
    • 2022-07-06
    • 2022-11-20
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多