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

在R中带lookaround的Regexpr

  •  0
  • SeGa  · 技术社区  · 6 年前

    我在试着得到 在字符串中(255;0;0).

    我没有设法找出R中的lookaheads,这对这个任务应该是有用的,所以我必须结合一个 regexpr+regmatches 有2个后续的 gsub 电话。

    string <- "<params description=\"some desc\" bgcol=\"248;186;203\" col=\"0;200;0\"/>"
    string <- "<params description=\"some desc\" bgcol=\"255;0;0\"/>"
    
    
    bgcol = regmatches(string, regexpr('(bgcol=\"(.*)\")', string, perl=TRUE))
    bgcol = gsub(pattern = "\"", replacement="", bgcol)
    bgcol = gsub(pattern = "bgcol=", replacement="", bgcol)
    
    as.integer(strsplit(bgcol, ";")[[1]])
    

    [1] 255 0 0

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

    regmatches / regexec :

    string <- "<params description=\"some desc\" bgcol=\"255;0;0\"/>"
    lapply(strsplit(regmatches(string, regexec('bgcol="([^"]*)"', string))[[1]][2], ";"), as.integer)
    ## => [[1]]
    ##    [1] 255   0   0
    

    bgcol="([^"]*)" bgcol=" ,然后匹配并捕获除 " 进入第1组( regexec 跟踪所有捕获的子字符串),然后匹配 .

    正则匹配 regexpr :

    lapply(strsplit(regmatches(string, regexpr('bgcol="\\K[^"]*', string, perl=TRUE)), ";"), as.integer)
    ## => [[1]]
    ##    [1] 255   0   0
    

    看到了吗 online R demo

    bgcol="\\K[^"]* 模式匹配 bgcol=“ \K 匹配重置运算符,并且仅与匹配的文本 [^"]* 仍在比赛中。

    stringr 解决:

    > library(stringr)
    > lapply(strsplit(str_extract(string, '(?<=bgcol=")[^"]*'), ";"), as.integer)
    [[1]]
    [1] 255   0   0
    
    > lapply(strsplit(str_match(string, 'bgcol="([^"]*)"')[,2], ";"), as.integer)
    [[1]]
    [1] 255   0   0
    

    请注意 (?<=bgcol=") str_extract 函数只检查 bgcol=“

        2
  •  2
  •   Jilber Urbina    6 年前

    你可以用这个图案 '.*bgcol=\"(\\d*;\\d*;\\d*)\"\\s?.*'

    > bgcol <- gsub('.*bgcol=\"(\\d*;\\d*;\\d*)\"\\s?.*', "\\1", strings)
    > lapply(strsplit(bgcol, ";"), as.integer)
    [[1]]
    [1] 255   0   0
    
    [[2]]
    [1] 248 186 203
    
        3
  •  0
  •   Onyambu    6 年前

    你可以用 read.table

    read.table(text = gsub('.*bgcol.*?(\\d+;\\d+;\\d+).*', '\\1', string), sep=';')
       V1  V2  V3
    1 248 186 203
    2 255   0   0
    
        4
  •  0
  •   Nettle    6 年前

    df <- tibble(string <- c("<params description=\"some desc\" bgcol=\"248;186;203\" col=\"0;200;0\"/>",
                "<params description=\"some desc\" bgcol=\"255;0;0\"/>"))
    

      df %>% mutate(bgcol.value = str_extract(string, "\\d+;\\d+;\\d+")) 
    
    # A tibble: 2 x 2
      `string <- c("<params description=\\"some desc\\" bgcol=\\"248;186;203\\" … bgcol.value
      <chr>                                                                       <chr>      
    1 "<params description=\"some desc\" bgcol=\"248;186;203\" col=\"0;200;0\"/>" 248;186;203
    2 "<params description=\"some desc\" bgcol=\"255;0;0\"/>"                     248;186;203