繁体   English   中英

R 正则表达式与 gsub

[英]R Regex expression with gsub

我正在使用 gsub 正则表达式来 select 表达式的最后一部分

例子:

  • “Bla-text-01” - 我想要 -> “text-01”
  • “名称-xpto-08”-我想要->“xpto-08”
  • “text-text-04” - 我想要 -> “text-04”
  • “new-blaxpto-morexpto-07”-我想要->“morexpto-07”
  • “new-new-new-bla-ready-05” - 我想要 -> “ready-05”

我创建了适用于前 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM