[英]Remove all characters between two other characters (keeping the other characters)
I know this question has been asked multiple times in different ways, but I can't find a solution where I would replace the text between some "borders" while keeping the borders.我知道这个问题已经以不同的方式多次被问到,但我找不到一个解决方案,我可以在保留边界的同时替换一些“边界”之间的文本。
input <- "this is my 'example'"
change <- "test"
And now I want to replace everything between teh single quotes with the value in change
.现在我想用
change
中的值替换单引号之间的所有内容。
Expected output would be "this is my 'test'
预期 output 将是
"this is my 'test'
I tried different variants of:我尝试了不同的变体:
stringr::str_replace(input, "['].*", change)
But it doesn't work.但它不起作用。 Eg the one above gives
"this is my test"
, so it doesn't have the single quotes anymore.例如上面的那个给出了
"this is my test"
,所以它不再有单引号了。
Any ideas?有任何想法吗?
You can use您可以使用
stringr::str_replace_all(input, "'[^']*'", paste0("'", change, "'"))
gsub("'[^']*'", paste0("'", change, "'"), input)
Or, you may also capture the apostophes and then use backreferences, but that would look uglier (cf. gsub("(')[^']*(')", paste0("\\1",change,"\\2"), input)
).或者,您也可以捕获撇号然后使用反向引用,但这看起来更丑陋(参见
gsub("(')[^']*(')", paste0("\\1",change,"\\2"), input)
)。
See the R demo online:在线看R演示:
input <- "this is my 'example'"
change <- "test"
stringr::str_replace_all(input, "'[^']*'", paste0("'", change, "'"))
gsub("'[^']*'", paste0("'", change, "'"), input)
Output: Output:
[1] "this is my 'test'"
[1] "this is my 'test'"
Note : if your change
variable contains a backslash, it must be doubled to avoid issues:注意:如果您的
change
变量包含反斜杠,则必须将其加倍以避免出现问题:
stringr::str_replace_all(input, "'[^']*'", paste0("'", gsub("\\", "\\\\", change, fixed=TRUE), "'"))
gsub("'[^']*'", paste0("'", gsub("\\", "\\\\", change, fixed=TRUE), "'"), input)
Using sub()
we can try:使用
sub()
我们可以尝试:
input <- "this is my 'example'"
change <- "test"
output <- sub("'.*?'", paste0("'", change, "'"), input)
output
[1] "this is my 'test'"
And this way?这样呢?
input <- "this is my 'example'"
change <- "test"
stringr::str_replace(input, "(?<=').*?(?=')", change)
(?<=') ← look the character before is a ' without catching it. (?<=') ← 看前面的字符是'没有抓住它。
. . ← catch any characters but as less as possible.
← 捕获任何字符,但尽可能少。 To covert a case like "this is my 'example' did you see 'it' "
隐藏一个案例,比如“这是我的‘例子’,你看到‘它’了吗”
(?=') ← look the character following is a ' without catching it. (?=') ← 看下面的字符是'没有捕捉到它。
↓ Tested here ↓ ↓ 在这里测试 ↓
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.