讓我們假設你需要匹配以'
啓動所有非重疊的子串,則比其他'
1個或多個字符,然後用'
結束。該模式是'[^']+'
。
然後,可以使用下面的基礎R代碼:
x = "The 'quick cunning brown' fox 'jumps up and over' the lazy dog"
gr <- gregexpr("'[^']+'", x)
mat <- regmatches(x, gr)
regmatches(x, gr) <- lapply(mat, gsub, pattern="\\s", replacement="_")
x
## => [1] "The 'quick_cunning_brown' fox 'jumps_up_and_over' the lazy dog"
this R demo見。或者,使用gsubfn
:
> library(gsubfn)
> rx <- "'[^']+'"
> s = "The 'quick cunning brown' fox 'jumps up and over' the lazy dog"
> gsubfn(rx, ~ gsub("\\s", "_", x), s)
[1] "The 'quick_cunning_brown' fox 'jumps_up_and_over' the lazy dog"
>
爲了支持轉義序列,你可以使用一個更復雜的PCRE正則表達式:
(?<!\\)(?:\\{2})*\K'[^'\\]*(?:\\.[^'\\]*)*'
詳細:
(?<!\\)
- 沒有\
之前當前位置
(?:\\{2})*
- 零個或更多個序列2 \
小號
\K
- 匹配復位操作者
'
- 單引號
[^'\\]*
- 零個或更多 - 零個或多個字符比'
和\
(?:\\.[^'\\]*)*
其他序列:
\\.
- a \
後跟任何c哈日但一個換行符
[^'\\]*
- 零個或多個字符比'
和\
'
其他 - 一個單引號。
而且R demo會是什麼樣
x = "The \\' \\\\\\' \\\\\\\\'quick \\'cunning\\' brown' fox 'jumps up \\'and\\' over' the lazy dog"
cat(x, sep="\n")
gr <- gregexpr("(?<!\\\\)(?:\\\\{2})*\\K'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'", x, perl=TRUE)
mat <- regmatches(x, gr)
regmatches(x, gr) <- lapply(mat, gsub, pattern="\\s", replacement="_")
cat(x, sep="\n")
輸出:
The \' \\\' \\\\'quick \'cunning\' brown' fox 'jumps up \'and\' over' the lazy dog
The \' \\\' \\\\'quick_\'cunning\'_brown' fox 'jumps_up_\'and\'_over' the lazy dog
只有當你有一個庸俗的頭腦;) – geotheory
你需要考慮內部轉義序列?你正在處理正確逃脫的字符串?如果您可以匹配整個相關的「....」子字符串,那麼您可以替換匹配內的任何文本。 –