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

提取模式Regex的两个引用

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

    input <- c("fdsfs iwantthis (1,1,1,1) fdsaaa   iwantthisaswell (2,3,4,5)", "fdsfs thistoo (1,1,1,1)")
    

    我想使用正则表达式来提取以下内容:

    > output
    [1] "iwantthis iwantthisaswell" "thistoo"
    

    我试着只听到第一个字:

    > gsub(".*?[[:space:]](.*?)[[:space:]]\\(.*", "\\1", input)
    [1] "iwantthis" "thistoo"  
    

    但我不能让它在多次出现的情况下工作:

        > gsub(".*?[[:space:]](.*?)[[:space:]]\\(.*?[[:space:]](.*?)[[:space:]]\\(.*", "\\1 \\2", input)
    [1] "iwantthis iwantthisaswell" "fdsfs thistoo (1,1,1,1)"  
    

    我管理的最接近的是:

    library(stringr)
    > str_extract_all(input, "(\\S*)\\s\\(")
    [[1]]
    [1] "iwantthis ("       "iwantthisaswell ("
    
    [[2]]
    [1] "thistoo ("
    

    我确信我在正则表达式中遗漏了一些东西(不太擅长),但是什么呢?

    3 回复  |  直到 6 年前
        1
  •  3
  •   Wiktor Stribiżew    6 年前

    你可以用

    > sapply(str_extract_all(input, "\\S+(?=\\s*\\()"), paste, collapse=" ")
    [1] "iwantthis iwantthisaswell" "thistoo"
    

    看到了吗 regex demo . 这个 \\S+(?=\\s*\\() 将从 ( 字符前面有0+空格。 sapply 具有 paste 将用空格(与)连接找到的匹配项 collapse=" "

    图案细节

    • \S+ -一个或多个非空白字符
    • (?=\s*\() -积极的展望( (?=...) )需要0+个空格字符( \s* )然后是一个 ( 字符( \( )立即到当前位置的右侧。
        2
  •  1
  •   akrun    6 年前

    base R

    unlist(regmatches(input, gregexpr("\\w+(?= \\()", input, perl = TRUE)))
    #[1] "iwantthis"       "iwantthisaswell" "thistoo"  
    
        3
  •  0
  •   krads    6 年前

    这适用于R:

    gsub('\\w.+? ([^\\s]+) \\(.+?\\)','\\1', input, perl=TRUE)
    

    [1] "iwantthis iwantthisaswell" "thistoo" 
    

    使用其他建议的一般案例输入:

    general_cases <- c("fdsfs iwantthis (1,1,1,1) fdsaaa   iwantthisaswell (2,3,4,5)", 
                       "fdsfs thistoo (1,1,1,1) ",
                       "GaGa iwant_this (1,1,1,1)", 
                       "lal2!@#$%^&*()_+a i_wantthisaswell2 (2,3,4,5)")
    gsub('\\w.+? ([^\\s]+) \\(.+?\\)','\\1', general_cases, perl=TRUE)
    

    [1] "iwantthis iwantthisaswell" "thistoo "                 
    [3] "iwant_this"                "i_wantthisaswell2"