繁体   English   中英

删除其他两个字符之间的所有字符(保留其他字符)

[英]Remove all characters between two other characters (keeping the other characters)

我知道这个问题已经以不同的方式多次被问到,但我找不到一个解决方案,我可以在保留边界的同时替换一些“边界”之间的文本。

input <- "this is my 'example'"
change <- "test"

现在我想用change中的值替换单引号之间的所有内容。

预期 output 将是"this is my 'test'

我尝试了不同的变体:

stringr::str_replace(input, "['].*", change)

但它不起作用。 例如上面的那个给出了"this is my test" ,所以它不再有单引号了。

有任何想法吗?

您可以使用

stringr::str_replace_all(input, "'[^']*'", paste0("'", change, "'"))
gsub("'[^']*'", paste0("'", change, "'"), input)

或者,您也可以捕获撇号然后使用反向引用,但这看起来更丑陋(参见gsub("(')[^']*(')", paste0("\\1",change,"\\2"), input) )。

在线看R演示:

input <- "this is my 'example'"
change <- "test"
stringr::str_replace_all(input, "'[^']*'", paste0("'", change, "'"))
gsub("'[^']*'", paste0("'", change, "'"), input)

Output:

[1] "this is my 'test'"
[1] "this is my 'test'"

注意:如果您的change变量包含反斜杠,则必须将其加倍以避免出现问题:

stringr::str_replace_all(input, "'[^']*'", paste0("'", gsub("\\", "\\\\", change, fixed=TRUE), "'"))
gsub("'[^']*'", paste0("'", gsub("\\", "\\\\", change, fixed=TRUE), "'"), input)

使用sub()我们可以尝试:

input <- "this is my 'example'"
change <- "test"
output <- sub("'.*?'", paste0("'", change, "'"), input)
output

[1] "this is my 'test'"

这样呢?

input <- "this is my 'example'"
change <- "test"

stringr::str_replace(input, "(?<=').*?(?=')", change)

(?<=') ← 看前面的字符是'没有抓住它。
. ← 捕获任何字符,但尽可能少。 隐藏一个案例,比如“这是我的‘例子’,你看到‘它’了吗
(?=') ← 看下面的字符是'没有捕捉到它。

↓ 在这里测试 ↓

意念

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM