[英]add characters before special characters in a string
I would like to add some characters to a string before a special character "(" and after the special character ")" 我想在字符串中的特殊字符“(”之前和特殊字符“)”之后添加一些字符
The position of "(" and ")" changes from one string to the next. “(”和“)”的位置从一个字符串更改为下一个字符串。
If it helps, I tried several ways, but I don't know how to piece it back together. 如果有帮助,我尝试了几种方法,但是我不知道如何将其拼凑起来。
a <- "a(b"
grepl("[[:punct:]]", a) #special character exists
x <- "[[:punct:]]"
image <- str_extract(a, x) #extract special character
image
eg 例如
"I want to go out (i.e. now). "
And the result to look like: 结果看起来像:
"I want to go out again (i.e. now) thanks."
I want to add "again" and "thanks" to the sentence. 我想在句子中添加“再次”和“谢谢”。
Thank you for helping! 感谢您的帮助!
Use str_replace
使用
str_replace
library(stringr)
str_replace("I want to go out (i.e. now).", "\\(", "again (") %>%
str_replace("\\)", ") thanks")
We can use sub
. 我们可以使用
sub
。 Match the characters inside the brackets including the brackets, capture it as a group, and we replace it with adding 'again' followed by the backreference of the captureed group ( \\\\1
) followed by 'thanks' 匹配方括号内的字符(包括方括号),将其捕获为一个组,然后将其替换为添加“再次”,捕获组的后向引用(
\\\\1
)和“感谢”
sub("(\\([^)]+\\))\\..*", "again \\1 thanks.", str1)
#[1] "I want to go out again (i.e. now) thanks."
Or using two capture groups 或使用两个捕获组
sub("(\\([^)]+\\))(.*)\\s+", "again \\1 thanks\\2", str1)
#[1] "I want to go out again (i.e. now) thanks."
str1 <- "I want to go out (i.e. now). "
NOTE: Using only base R
注意:仅使用
base R
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.