【问题标题】:R regex can replace opening bracket but not closing bracketR 正则表达式可以替换左括号但不能替换右括号
【发布时间】:2016-10-05 07:43:55
【问题描述】:

我正在尝试替换字符串中的左括号和右括号。 R 似乎是为左括号做的:

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

但不是右括号

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

为什么会这样?

【问题讨论】:

  • 据我了解,问题是关于在括号表达式/字符类中使用[],对吧?还有其他答案涉及其他内容,因此,调整问题标题和问题本身可能是个好主意。

标签: r regex gsub brackets square-bracket


【解决方案1】:

看,gsub("[\\]]","==","hello\\] [world]")[\]] 中的模式实际上匹配了 \ 后跟 ]。尝试gsub("[\\]]","==","hello\\] [world]"),结果将是hello== [world],文字反斜杠将被替换。

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

作为"[\\]]" 正则表达式的修复,您可以从模式中删除\

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

this R online demo

您可以在 PCRE 模式中对其进行转义,因为 PCRE 字符类 允许其中包含转义字符:

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

another demo

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

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

【讨论】:

  • 谢谢。要做到这两点,gsub("[\\[]]","==","Hello [World]" 不起作用,但 gsub("[]\\[]","==","Hello [World]") 起作用。这有什么押韵或原因吗?
  • 仅供参考:[...] 中的 ] 在被放置在打开的 [ 之后被视为文字 ],因此,[][] 有效匹配文字 @987654346 @ 或文字 ].
  • 在 TRE 正则表达式中,括号表达式中的反斜杠被视为文字反斜杠。在您的"[]\\[]" 中,您匹配]\[。请参阅this R demo,其中gsub("[]\\[]","==", "Hello \\ [World]") 替换输入字符串中的 3 个字符。
【解决方案2】:

这很简单:

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

【讨论】:

    【解决方案3】:

    使用stringi 可能更易读/更直接,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 2013-03-13
      相关资源
      最近更新 更多