Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在字符串中的特殊字符之前添加字符_R - Fatal编程技术网

R 在字符串中的特殊字符之前添加字符

R 在字符串中的特殊字符之前添加字符,r,R,我想在特殊字符“(“特殊字符”之后)之前向字符串添加一些字符 “(“and”)的位置从一个字符串更改为下一个字符串 如果有帮助的话,我尝试了几种方法,但我不知道如何把它们重新组合起来 a <- "a(b" grepl("[[:punct:]]", a) #special character exists x <- "[[:punct:]]" image <- str_extract(a, x) #extract special character image 结果是: "

我想在特殊字符“(“特殊字符”之后)之前向字符串添加一些字符

“(“and”)的位置从一个字符串更改为下一个字符串

如果有帮助的话,我尝试了几种方法,但我不知道如何把它们重新组合起来

a <- "a(b"
grepl("[[:punct:]]",  a) #special character exists
x <- "[[:punct:]]" 
image <- str_extract(a, x) #extract special character
image
结果是:

"I want to go out again (i.e. now) thanks."
我想在句子后面加上“再次”和“谢谢”


谢谢你的帮助

我们可以使用
sub
。匹配括号内的字符(包括括号),将其捕获为一个组,我们将其替换为添加“再次”,然后添加捕获组的反向引用(
\\1
),然后添加“谢谢”

sub("(\\([^)]+\\))\\..*", "again \\1 thanks.", str1)
#[1] "I want to go out again (i.e. now) thanks."
或者使用两个捕获组

sub("(\\([^)]+\\))(.*)\\s+", "again \\1 thanks\\2", str1)
#[1] "I want to go out again (i.e. now) thanks."
数据
str1我们可以使用
sub
。匹配括号内的字符(包括括号),将其捕获为一个组,我们将其替换为添加“再次”,然后添加捕获组的反向引用(
\\1
),然后添加“谢谢”

sub("(\\([^)]+\\))\\..*", "again \\1 thanks.", str1)
#[1] "I want to go out again (i.e. now) thanks."
或者使用两个捕获组

sub("(\\([^)]+\\))(.*)\\s+", "again \\1 thanks\\2", str1)
#[1] "I want to go out again (i.e. now) thanks."
数据
str1使用
str\u替换

 library(stringr)
 str_replace("I want to go out (i.e. now).", "\\(", "again (") %>%
   str_replace("\\)", ") thanks")

使用
str\u替换

 library(stringr)
 str_replace("I want to go out (i.e. now).", "\\(", "again (") %>%
   str_replace("\\)", ") thanks")

“)”不一定在句末。让我来更新一下。我试过了,但好像出了个错误<代码>str1@Sam我没有收到任何数据错误。我将数据添加为well@akrun它在R控制台本身工作,但使用rstudio似乎可以排除错误。不管怎样,它是有效的。非常感谢。可能是
sub((.*)(\\([^)]+\\)(.*)”、“\\1增益\\2感谢\\3”,str1)
而不是手动在句末添加句点?该“)”不一定在句末。让我来更新一下。我试过了,但好像出了个错误<代码>str1@Sam我没有收到任何数据错误。我将数据添加为well@akrun它在R控制台本身工作,但使用rstudio似乎可以排除错误。不管怎样,它是有效的。非常感谢。是否可以使用
sub((.*)(\\([^)]+\\)(.*),“\\1增益\\2感谢\\3”,str1)
而不是在末尾手动添加句点?