stringr::str_extract
approach
您可以使用
example <- c("positive_1", "positive_2", "test_20_curve", "test_60_point", "percent_total")
library(stringr)
str_extract(example, "(?<!\\d)\\d{2}(?!\\d)")
## => [1] NA NA "20" "60" NA
请看R demo.Note:str_extract
提取模式的first个匹配项.如果您需要最后一个,请使用library(stringi)
,然后使用stri_extract_last_regex(example, "(?<!\\d)\\d{2}(?!\\d)")
.
Details:
(?<!\d)
-紧靠左侧,不能有数字
\d{2}
-两位数
(?!\d)
--后面不会紧跟另一个数字.
sub
approach
example <- c("positive_1", "positive_2", "test_20_curve", "test_60_point", "percent_total")
res <- sub("^(?:(?:.*\\D)?(\\d{2})(?:\\D.*)?|.+)$", "\\1", example)
res <- res[nzchar(res)]
res
## => [1] "20" "60"
请看R demo.
Pattern details个
^
-字符串的开始
(?:
- either of the two alternatives:
- |.+)
(?:.*\D)?
-任意非数字字符的可选序列,然后是字符串的其余部分
(\d{2})
-第一组(替换图案中的\1
指值):两位
(?:\D.*)?
-任意非数字字符的可选序列,然后是字符串的其余部分
|
- or
)
-外部分组的末尾(以便任一模式部分可以匹配整个字符串)
$
-字符串末尾.
注sub
在这里就足够了,因为我们在匹配整个字符串时执行一次替换.
如果字符串中没有只有两位数的数字,则sub
的结果将是空字符串,所以我们需要使用res <- res[nzchar(res)]
来go 掉它们.
NOTE:如果两位数字多次出现,则使用此方法返回最后一个.要获得第一个,请使用sub("^(?:(?:.*?\\D)?(\\d{2})(?:\\D.*)?|.+)$", "\\1", example, perl=TRUE)
.