带 gsub 的 R 正则表达式
R Regex expression with gsub
我正在使用 gsub 正则表达式 select 表达式的最后一部分
示例:
- “Bla-text-01”-我想要 ->“text-01”
- "Name-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")
我正在使用 gsub 正则表达式 select 表达式的最后一部分
示例:
- “Bla-text-01”-我想要 ->“text-01”
- "Name-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")