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

从字符表中提取长度为(1 | 2)的数字字符

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

    # Data comes in as a long string
    Test<-("82026-424 82026-424 1 CSX10 Store Room 75.74 75.74")
    
    # Seperate data into individual pieces with str_split
    Split_Test<-str_split(Test[1],"\\s+")
    
    # We can easily unlist it with the following code (Not sure if needed)
    Test_Unlisted<-unlist(Split_Test)
    
    > Test_Unlisted
    [1] "82026-424" "82026-424" "1"         "CSX10"     "Store"     "Room"      
    [8] "75.74" "75.74"
    

    我期望的结果是从字符列表中得到“1”,然后如果值是“20”,也可以识别它。

    Test_Final<-str_match(Test_Unlisted, "\\d|\\d\\d")
    

    使用此代码,我可以获取长度为1的任何内容,但不能保证它是一个字符:

    Test_Final<-which(sapply(Test_Unlisted, nchar)==1)
    

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

    你需要使用

    Test<-("82026-424 82026-424 1 CSX10 Store Room 75.74 75.74, 20")
    regmatches(Test, gregexpr("\\b(?<!\\d\\.)\\d{1,2}\\b(?!\\.\\d)", Test, perl=TRUE))
    

    regex demo regex demo .

    • \b
    • (?<!\d\.) -如果在当前位置的左边有一个数字和一个点,则匹配失败的一种反向查找
    • \d{1,2} -1或2位数
    • -词界
    • (?!\.\d) -如果在当前位置的右边有一个点和一个数字,则匹配失败的一种负向前看。

    注意,由于模式中使用了lookarounds,regex应该传递给PCRE regex引擎,因此 perl=TRUE

    stringr

    library(stringr)
    str_extract_all(Test, "\\b(?<!\\d\\.)\\d{1,2}\\b(?!\\.\\d)")