提取带有正负号的数字

问题描述 投票:2回答:1

我在使用+/-标志提取数字之前遇到了麻烦。

我的示例字符串是这样的

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 

after_slash

-1 1 -2

我该如何解决这个问题?

r regex
1个回答
2
投票

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位或更多位数
© www.soinside.com 2019 - 2024. All rights reserved.