簡體   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