簡體   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