2

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

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

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

4

3 回答 3

1

我只是在末端|被移除的情况下使用拆分。我只会拿第三个元素和奇数元素之后的东西。

    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 );
于 2013-12-17T13:39:16.843 回答
1

一种解决方案是去除开头的字符(我已经用 a 完成了此操作,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" 
于 2013-12-17T14:15:22.803 回答
1

另一个

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" 
于 2013-12-17T14:19:41.150 回答