[英]R regex can replace opening bracket but not closing bracket
I am trying to replace opening and closing brackets in a string. 我试图替换字符串中的开始和结束括号。 R seems to do it for the opening bracket:
R似乎是为开场括号做的:
> gsub("[\\[]","==","hello [world]")
[1] "hello ==world]"
but not for the closing brackets 但不是关闭括号
> gsub("[\\]]","==","hello [world]")
[1] "hello [world]"
Why is this so? 为什么会这样?
Look, the pattern in gsub("[\\\\]]","==","hello\\\\] [world]")
, [\\]]
, is effectively matching a \\
followed with ]
. 看,
gsub("[\\\\]]","==","hello\\\\] [world]")
, [\\]]
中的模式实际上匹配了一个\\
后跟与]
。 Try gsub("[\\\\]]","==","hello\\\\] [world]")
, and the result will be hello== [world]
, the literal backslash will get replaced. 尝试
gsub("[\\\\]]","==","hello\\\\] [world]")
,结果将是hello== [world]
,文字反斜杠将被替换。
In a TRE regex pattern, a \\
inside a bracket expression matches a literal backslash. 在TRE正则表达式模式中,括号表达式中的
\\
与文字反斜杠匹配。
As a fix for your "[\\\\]]"
regex, you may remove the \\
from the pattern: 作为
"[\\\\]]"
正则表达式的修复,您可以从模式中删除\\
:
gsub("[[]","==","hello [world]")
See this R online demo . 请参阅此R在线演示 。
You may escape it in a PCRE pattern though, as PCRE character classes allow escaped characters inside them: 您可以在PCRE模式中将其转义,因为PCRE 字符类允许其中的转义字符:
gsub("[\\[]","==","hello [world]", perl=TRUE)
See another demo 看另一个演示
If you need to replace either [
or ]
, just put the ][
inside the bracket expression: 如果你需要替换
[
或]
,只需将][
放在括号表达式中:
gsub("[][]","==","hello [world]")
This simply works: 这简单有效:
gsub("]", "==","hello [world]")
#"hello [world=="
A maybe more readable/straight forward way to do it is with stringi
, 一个可能更可读/更直接的方法是使用
stringi
,
library(stringi)
stri_replace_all_regex('hello [world]', '\\[|]', '==')
#[1] "hello ==world=="
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.