我在使用+/-
标志提取数字之前遇到了麻烦。
我的示例字符串是这样的
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
我该如何解决这个问题?
regmatches(x, regexpr("[-+]?\\d+(?=/)", x, perl=TRUE))
str_extract(x, "[-+]?\\d+(?=/)")
细节
[-+]?
- 可选的-
或+
\d+
- 1位或更多位数(?=/)
- 当前位置的右侧必须有斜线regmatches(x, regexpr("/\\K[-+]?\\d+", x, perl=TRUE))
str_extract(x, "(?<=/)[-+]?\\d+")
见R demo。
细节
/
- 斜线\K
- 匹配重置运算符,丢弃到目前为止匹配的所有文本[-+]?
- 可选的-
或+
\d+
- 1位或更多位数