Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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_String - Fatal编程技术网

替换“$&引用;在R的字符串中

替换“$&引用;在R的字符串中,r,string,R,String,我想替换我的R字符串中的$。我试过: mystring <- "file.tree.id$HASHd15962267-44c21f1cee1057d95d6840$HASHe92451fece3b3341962516acfa962b2f$checked" stringr::str_replace(mystring, pattern="$", replacement="!") 我尝试了一些使用“p

我想替换我的R字符串中的
$
。我试过:

mystring <- "file.tree.id$HASHd15962267-44c21f1cee1057d95d6840$HASHe92451fece3b3341962516acfa962b2f$checked"

 stringr::str_replace(mystring, pattern="$", 
              replacement="!")

我尝试了一些使用
“pattern=“/$”
的变体,但也失败了。有人能指出一个策略来做到这一点吗?

我们需要
固定的
被包装,因为默认情况下
pattern
处于
regex
模式,而regex
$
意味着字符串结束

stringr::str_replace_all(mystring, pattern = fixed("$"), 
              replacement = "!")

或者可以转义(
\\$
)或将其放在方括号中(
[$]$
),但“修复”会更快

我们需要将
修复
包装,因为默认情况下
模式
处于
regex
模式,而regex
$
意味着字符串结束

stringr::str_replace_all(mystring, pattern = fixed("$"), 
              replacement = "!")

或者可以转义(
\\$
)或将其放在方括号中(
[$]$
),但“修复”会更快,在基数R中,您可以使用:

chartr("$","!", mystring)
[1] "file.tree.id!HASHd15962267-44c21f1cee1057d95d6840!HASHe92451fece3b3341962516acfa962b2f!checked"
甚至

 gsub("$","!", mystring, fixed = TRUE)

在base R中,您可以使用:

chartr("$","!", mystring)
[1] "file.tree.id!HASHd15962267-44c21f1cee1057d95d6840!HASHe92451fece3b3341962516acfa962b2f!checked"
甚至

 gsub("$","!", mystring, fixed = TRUE)

感谢您的解决方案。但是它似乎只替换字符串中的第一个
$
。stringr::str_replace(mystring,pattern=fixed(“$”),+replacement=“!”[1]”file.tree.id!哈希值15962267-44c21f1cee1057d95d6840美元哈希值92451ECE3B3341962516ACFA962B2F美元已检查“@user3091668抱歉,之前没有检查您的字符串。您需要
str\u replace\u all
,因为
str\u replace
只会在第一时间进行替换,这是解决方案的关键。但是,它似乎只替换字符串中的第一个
$
。stringr::str_replace(mystring,pattern=fixed(“$”,+replacement=“!”[1]”file.tree.id!HASHd15962267-44c21f1cee1057d95d6840$HASHe92451fece3b3341962516acfa962b2f$checked“@user3091668抱歉,之前没有检查您的字符串。您需要
str\u replace\u all
,因为
str\u replace
只在第一个实例上进行替换