如何使用正则表达式提取字符串的最后一位?

How to extract the last digits of strings using regular expressions?

我有一堆colnames

L_1_3
L_2_23
L_3_91
L_3_16

我想使用 _ 后的最后一位数字将这些别名替换为新名称,如下所示:

3
23
91
16

我试过 colnames(X) <- gsub("L_\d\d_", "", colnames(X)),它适用于末尾有两位数的字符串。我想要一个适用于一位数和两位数的。

谢谢!

这是执行此操作的正则表达式。
它得到任何东西,直到一个非数字后面跟着一个或多个数字的捕获组。并替换为捕获组。

sub('.*[^[:digit:]]{1}([[:digit:]]+$)', '\1', x)
#[1] "3"  "23" "91" "16"

适用于个位数和双位数但不多也不少的正则表达式

sub('.*[^[:digit:]]{1}([[:digit:]]{1,2}$)', '\1', x)
#[1] "3"  "23" "91" "16"

数据

x <- scan(what = character(), text = '
L_1_3
L_2_23
L_3_91
L_3_16')

这是一个正向预测的选项:

gsub(".+_(?=\d+$)", "", X, perl = TRUE)
[1] "3"  "23" "91" "16"

尽量保持简单

sub(".*_(\d+$)", "\1", X)
[1] "3"  "23" "91" "16"

我们可以使用str_extract

library(stringr)
str_extract(X, "\d+$")
#[1] "3"  "23" "91" "16"

数据

X <- c("L_1_3", "L_2_23", "L_3_91", "L_3_16")

如果这是适用于 2 位数字的模式,您唯一需要做的就是使用 ?

将其中一位数字设为可选
L_\d\d?_

Regex demo | R demo


如果您必须匹配整个模式,您可以使用捕获组并使用锚点断言字符串的开始 ^ 和结束 $ 并在替换中使用该组。

^L_\d\d?_(\d+)$

部分

^      Start of string
L_     Match L_
\d     Match a digit
\d?    Match a digit and repeat 0 or 1 times
_      Match _
(      Capture group 1
  \d+  Match a digit and repeat 1 or more times
)      Close group
$      End of string

Regex demo | R demo

X <- c("L_1_3", "L_2_23", "L_3_91", "L_3_16")
gsub("^L_\d\d?_(\d+)$", "\1", X)

输出

[1] "3"  "23" "91" "16"

我认为这可能是最简单的正则表达式:

sub(".*\_", "", tmp)