【问题标题】:Extract multiple recurring text patterns提取多个重复出现的文本模式
【发布时间】:2013-12-17 13:33:45
【问题描述】:

我有一个看起来像这样的字符串:

txt <- "|M  CHG  6  44  -1  48  -1  53  -1  63   1  64   1  65   1|"

第一个数字 (6) 表示模式 \\s+\\d+\\s+[\\+-]?\\d+ 重复出现 6 次。实际上我只对这种模式的第二个(可能有符号的)数字感兴趣。所以我正在寻找一个给我结果的函数或正则表达式

[1] "-1" "-1" "-1" "1" "1" "1"

我试过了

gsub( "^\\|M\\s+CHG\\s+\\d+(\\s+\\d+\\s+([\\+-]?\\d+))+\\|$", replacement="\\2", x=txt, perl=TRUE )

还有

str_replace_all( x, perl( "^\\|M\\s+CHG\\s+\\d+(\\s+\\d+\\s+([\\+-]?\\d+))+\\|$" ), "\\2" )

但在这两种情况下,我都只返回了最后一次出现。

【问题讨论】:

  • 你的字符串是否以相同的方式开始,即|M CHG \\d? \\d 是一位或多位数字?

标签: r regex stringr


【解决方案1】:

一种解决方案是去除开头的字符(我已经使用regex 完成了此操作,但您可能希望使用substr 或类似的。然后将matrix 放入所需的尺寸并返回您想要的列:

#  regex to strip superfluous characters
#  but `substring( txt , 10 )` would work just as well in this example
pat <- "^\\|M\\s+CHG\\s+\\d+\\s+(.*)\\|$"
x <- gsub( pat , "\\1" , txt )

#  Get result
matrix( unlist( strsplit( x , "\\s+" ) ) , ncol = 2 , byrow = 2 )[,2]
# [1] "-1" "-1" "-1" "1"  "1"  "1"

中间的matrix 看起来像这样:

#     [,1] [,2]
#[1,] "44" "-1"
#[2,] "48" "-1"
#[3,] "53" "-1"
#[4,] "63" "1" 
#[5,] "64" "1" 
#[6,] "65" "1" 

【讨论】:

    【解决方案2】:

    我只是在 上使用拆分,并删除了结尾 |。我只取第三个元素和奇数元素之后的内容。

        var txt, txtArray, result;
    
    txt = "|M  CHG  6  44  -1  48  -1  53  -1  63   1  64   1  65   1|";
    
    // Remove the end '|';
    txt = txt.slice(0, -1);
    
    // Split on one or more space...
    txtArray = txt.split(/\s+/);
    
    
    // Grab the odd ones only after the third element...
    result = txtArray.filter(function(n, i){
      return i > 3 && i % 2 === 0;
    });
    
    console.log( result );
    

    【讨论】:

    • 我刚刚意识到这不是我所知道的语言。如果有人需要,我已经在 J​​avascript 中添加了答案!
    【解决方案3】:

    另一个

    txt <- "|M  CHG  6  44  -1  48  -1  53  -1  63   1  64   1  65   1|"    
    
    
    #original
    #txtsplit<-unlist(strsplit(txt, "\\s+"))
    #n=as.numeric(txtsplit[3])
    #o<-txtsplit[4+seq(from=1, by=2, length.out=n)]
    
    #fixed
    txtsplit<-unlist(strsplit(txt, "\\||\\s+"))
    n=as.numeric(txtsplit[4])
    o<-txtsplit[5+seq(from=1, by=2, length.out=n)]
    
    #>o
    [1] "-1" "-1" "-1" "1"  "1"  "1" 
    

    【讨论】:

    • 您的示例产生一个“1|”作为strsplit 的最后一个元素,但仍然是最直接的解决方案。我将您的解决方案与@SimonO101 的gsub 结合在一起。
    • 是的,没错。我也应该摆脱|,很高兴它起作用了
    猜你喜欢
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2018-11-20
    • 1970-01-01
    • 2020-11-30
    相关资源
    最近更新 更多