[英]R Regex expression with gsub
我正在使用 gsub 正则表达式来 select 表达式的最后一部分
例子:
我创建了适用于前 3 个案例的代码,但现在我有一个新的请求也适用于 5 个案例。
gsub(x = match$id,
pattern = "(.*?-)(.*)",
replacement = "\\2")
你能帮助我吗?
x <- c("Bla-text-01",
"Name-xpto-08",
"text-text-04",
"new-blaxpto-morexpto-07",
"new-new-new-bla-ready-05")
sub("^.*-([^-]*-[^-]*)$", "\\1", x)
## [1] "text-01" "xpto-08" "text-04" "morexpto-07" "ready-05"
试试这个正则表达式:
sub(".*-(.*-.*)$", "\\1", x)
## [1] "text-01" "xpto-08" "text-04" "morexpto-07" "ready-05"
其他方法是:
# 2. use basename/dirname
xx <- gsub("-", "/", x)
paste(basename(dirname(xx)), basename(xx), sep = "-")
## [1] "text-01" "xpto-08" "text-04" "morexpto-07" "ready-05"
# 3. use scan
f <- function(x) {
scan(text = x, what = "", sep = "-", quiet = TRUE) |>
tail(2) |>
paste(collapse = "-")
}
sapply(x, f)
## Bla-text-01 Name-xpto-08 text-text-04
## "text-01" "xpto-08" "text-04"
## new-blaxpto-morexpto-07 new-new-new-bla-ready-05
## "morexpto-07" "ready-05"
以可重现的形式输入:
x <- c("Bla-text-01", "Name-xpto-08", "text-text-04", "new-blaxpto-morexpto-07",
"new-new-new-bla-ready-05")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.