[英]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.