【问题标题】:regular expression matching and replacing pvalue strings正则表达式匹配和替换 pvalue 字符串
【发布时间】:2015-03-31 08:25:09
【问题描述】:

希望这是有道理的。

我有一串不同长度的 pvalue(由于舍入),其中非常大和小的 pvalue 分别存储为 1.0(some number of 0s corresponding to the length of rounding)0.0(some number of 0s corresponding to the length of rounding)

我要匹配两组模式:

首先: "(1.)(string of zeros of any length)" 并将其更改为"> 0.(sting of nines the same length as the string of zeros)"

第二 "(0.)(string of zeros of any length)" 并将其更改为"< 0.(string of zeros the length of the input minus one)1

所以如果我们有以下输入:

pvals<-c("1.000","1.00","0.00000","0.123","0.6","0.0")

我希望返回:

> expectedOutput
[1] "> 0.999"   "> 0.99"    "< 0.00001" "0.123"     "0.6"       "< 0.1" 

我一直在尝试使用 gsub,但是我对正则表达式的更复杂的使用知之甚少我不明白如何允许某个字符 (0) 的任何长度,然后如何替换为相同数字的新字符(在 1.0s 的情况下),或该数字减 1(在 0.0s 的情况下)

任何帮助将不胜感激! 谢谢

【问题讨论】:

  • 我认为第一个元素的输出是&lt; 0.999
  • 不确定1.0001.00 之间有什么区别。 0.000000.00 之间都没有
  • 不,我想要所有以“1”开头的字符串。然后变成“> 0”。”
  • 这只是问题的简化。问题是我将收到 0.00000 和 0.0 的输入,我需要保持输入的完整性。
  • @AvainashRaj 啊,我的输入/输出是正确的,但我的规则被颠倒了。很抱歉造成混乱,并感谢您指出这一点。现在已经修好了。

标签: regex r


【解决方案1】:

你可以这样做,

> pvals<-c("1.000","1.00","0.00000","0.123","0.6","0.0")
> x <- gsub("(?:^1\\.|\\G)\\K0(?=0*$)", "9", pvals, perl=T)
> m <- gsub("^1\\.", "> 0.", x)
> gsub("^(0\\.0*)0$", "< \\11", m)
[1] "> 0.999"   "> 0.99"    "< 0.00001" "0.123"    
[5] "0.6"       "< 0.1"   

【讨论】:

  • 这看起来很棒。好吧,不幸的是,对我来说,它看起来就像一只猴子在敲击键盘,但效果很好。你有什么参考资料可以让我学习到这个级别的正则表达式吗?
  • 我从 SO 本身学到了所有正则表达式的东西。你可以参考this site..
【解决方案2】:

您也可以使用 gsubfn 包来执行此操作。

pvals <- c('1.000', '1.00', '0.00000', '0.123', '0.6', '0.0')

f <- proto(fun = function(this, x, y) 
   if (x==1) paste0('> 0.', paste(rep(9, nchar(y)), collapse = '')) 
   else paste0('< 0.', paste(rep(0, nchar(y)-1), collapse = ''), 1))

gsubfn('([01])\\.(0+)', f, pvals)
# [1] "> 0.999"   "> 0.99"    "< 0.00001" "0.123"     "0.6"       "< 0.1" 

【讨论】:

    猜你喜欢
    • 2015-11-30
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2011-09-02
    • 1970-01-01
    相关资源
    最近更新 更多