使用gsub从字符串中删除模式

时间:2021-08-18 16:53:38

I am struggling to remove the substring before the underscore in my string. I want to use * (wildcard) as the bit before the underscore can vary:

我正在努力删除字符串中下划线之前的子字符串。我想在下划线变化之前使用*(通配符)作为位:

a <- c("foo_5", "bar_7")

a <- gsub("*_", "", a, perl = TRUE)

The result should look like:

结果应如下所示:

> a
[1] 5 7

I also tried stuff like "^*" or "?" but did not really work.

我也试过像“^ *”或“?”这样的东西。但没有真正奏效。

3 个解决方案

#1


37  

The following code works on your example :

以下代码适用于您的示例:

gsub(".*_", "", a)

#2


5  

Alternatively, you can also try:

或者,您也可以尝试:

gsub("\\S+_", "", a)

#3


-2  

as.numeric(gsub(pattern=".*_", replacement = '', a)
[1] 5 7

#1


37  

The following code works on your example :

以下代码适用于您的示例:

gsub(".*_", "", a)

#2


5  

Alternatively, you can also try:

或者,您也可以尝试:

gsub("\\S+_", "", a)

#3


-2  

as.numeric(gsub(pattern=".*_", replacement = '', a)
[1] 5 7