【问题标题】:extract digits with positive and negative sign提取带正号和负号的数字
【发布时间】:2019-03-28 17:43:02
【问题描述】:

我无法提取带有+/- 符号的数字。

我的示例字符串是这样的

x <- c("alexander c/d=(+5/-1)","maximus a/b=(-4/1)", "thor e/d=(+3/-2)")

我尝试提取正斜杠 / 前后的数字及其符号。

所以我尝试了

before_slash=sub(".*=\\((-?\\d+).*","\\1", x, perl = TRUE)

给了

"alexander c/d=(+5/-1)" "-4"                    "thor e/d=(+3/-2)"

    after_slash=sub("^.*/(-?\\d+)","\\1", x, perl = TRUE)
> after_slash
[1] "-1)" "1)"  "-2)"

OTH,预期输出

before_slash

+5 -4 +3 

斜线后

-1 1 -2

我该如何解决这个问题?

【问题讨论】:

    标签: r regex


    【解决方案1】:

    Before slash:

    regmatches(x, regexpr("[-+]?\\d+(?=/)", x, perl=TRUE))
    str_extract(x, "[-+]?\\d+(?=/)")
    

    详情

    • [-+]? - 可选的 -+
    • \d+ - 1 位或多位数字
    • (?=/) - 当前位置右侧必须有一个斜线

    After slash:

    regmatches(x, regexpr("/\\K[-+]?\\d+", x, perl=TRUE))
    str_extract(x, "(?<=/)[-+]?\\d+")
    

    请参阅R demo

    详情

    • / - 斜线
    • \K - 匹配重置运算符丢弃所有匹配的文本
    • [-+]? - 可选的 -+
    • \d+ - 1 位或多位数字

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 2018-11-23
      • 2021-02-03
      相关资源
      最近更新 更多