1)子評論/ gsub這可以分解爲兩個簡單的sub/gsub調用。內部gsub
用空字符串替換不是數字或逗號的任何內容,並且外部將逗號轉換爲空格減號空格。
sub(",", " - ", gsub("[^0-9,]", "", vecA))
## [1] "0 - 10" "10 - 20" "20 - 30" "50 - 60" "90 - 100"
2)一個子要與一個sub
做到這一點:
sub("^\\D*(\\d+)\\D*(\\d+)\\D*$", "\\1 - \\2", vecA)
## "0 - 10" "10 - 20" "20 - 30" "50 - 60" "90 - 100"
3)串/讀取。表這其中不使用子或GSUB或任何正則表達式:
with(read.table(text = substring(vecA, 2, nchar(vecA)-1), sep = ","), paste(V1, "-", V2))
## [1] "0 - 10" "10 - 20" "20 - 30" "50 - 60" "90 - 100"
3a)的的這種變化(3)是稍短:
with(read.table(text = gsub("\\D", " ", vecA)), paste(V1, "-", V2))
## [1] "0 - 10" "10 - 20" "20 - 30" "50 - 60" "90 - 100"
4)gsubfn該提取物捕獲組和執行指示paste
:
library(gsubfn)
strapply(vecA, "(\\d+)\\D*(\\d+)", ~ paste(x, "-", y), simplify = c)
## [1] "0 - 10" "10 - 20" "20 - 30" "50 - 60" "90 - 100"
4A)(4),其使用stapplyc
而非strapply
的變異:
library(gsubfn)
sapply(strapplyc(vecA, "\\d+"), paste, collapse = " - ")
## [1] "0 - 10" "10 - 20" "20 - 30" "50 - 60" "90 - 100"
4B)的變化(4),其使用gsubfn而非strapply
:
library(gsubfn)
gsubfn("\\D+", ~ if (grepl(",", x)) " - " else "", vecA)
## [1] "0 - 10" "10 - 20" "20 - 30" "50 - 60" "90 - 100"
5) strsplit這是另一種不使用sub或gsub的解決方案:
f <- function(x) {
paste0(ifelse(x == ",", " - ", ifelse(x %in% 0:9, x, "")), collapse = "")
}
sapply(strsplit(vecA, ""), f)
## [1] "0 - 10" "10 - 20" "20 - 30" "50 - 60" "90 - 100"
我不知道你是否對你的正則表達式錯誤感興趣。提示:'(。*)'。 –