Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.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_Regex_Gsub_Brackets_Square Bracket - Fatal编程技术网

R正则表达式可以替换打开支架,但不能替换关闭支架

R正则表达式可以替换打开支架,但不能替换关闭支架,r,regex,gsub,brackets,square-bracket,R,Regex,Gsub,Brackets,Square Bracket,我试图替换字符串中的开始括号和结束括号。R似乎对开口支架起作用: > gsub("[\\[]","==","hello [world]") [1] "hello ==world]" 但不适用于结束括号 > gsub("[\\]]","==","hello [world]") [1] "hello [world]" 为什么会这样?看,gsub(“[\\]]”,“==”,“hello\\\][world]”,[\]中的模式有效地匹配了一个\,后跟]。尝试gsub(“[\\]]”、“=

我试图替换字符串中的开始括号和结束括号。R似乎对开口支架起作用:

> gsub("[\\[]","==","hello [world]")
[1] "hello ==world]"
但不适用于结束括号

> gsub("[\\]]","==","hello [world]")
[1] "hello [world]"

为什么会这样?

看,
gsub(“[\\]]”,“==”,“hello\\\][world]”
[\]
中的模式有效地匹配了一个
\
,后跟
]
。尝试
gsub(“[\\]]”、“==”、“hello\\][world]”
,结果将是
hello==[world]
,文字反斜杠将被替换

在TRE正则表达式模式中,括号表达式中的
\
与文本反斜杠匹配。

作为对
“[\\]]”
regex的修复,您可以从模式中删除
\

gsub("[[]","==","hello [world]")

但是,您可以在PCRE模式中转义它,因为PCRE字符类允许在其中转义字符:

gsub("[\\[]","==","hello [world]", perl=TRUE)

如果需要替换
[
]
,只需将
][
放在括号表达式内即可:

 gsub("[][]","==","hello [world]")
这很简单:

gsub("]", "==","hello [world]")
#"hello [world=="

使用
stringi
,可能更具可读性/更直接

library(stringi)
stri_replace_all_regex('hello [world]', '\\[|]', '==')
#[1] "hello ==world=="

谢谢。这两种方法都可以,
gsub([\\[]],“==”,“Hello[World]”
不起作用,但
gsub([\[]],“==”,“Hello[World]”
起作用。这有什么押韵或原因吗?仅供参考:
[…]
中的
][/code>放在打开的
[/code>之后时被视为文字
][/code>
有效地匹配一个文本
[
或一个文本
]
。在TRE正则表达式中,括号表达式中的反斜杠被视为一个文本反斜杠。在
“[]\[]”
中,您可以匹配
]
\
[
。请参阅where
gsub([]\[\[],“=”,“Hello\\[World]”)中的内容
替换输入字符串中的3个字符。据我所知,这个问题是关于在括号表达式/字符类中使用
[
]
的,对吗?还有其他答案是关于其他内容的,因此,调整问题标题和问题本身可能是个好主意。