让我们假设你需要匹配以'
启动所有非重叠的子串,则比其他'
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
你需要考虑内部转义序列?你正在处理正确逃脱的字符串?如果您可以匹配整个相关的“....”子字符串,那么您可以替换匹配内的任何文本。 –