【问题标题】:Opposite of Hmisc::escapeRegexHmisc::escapeRegex 的对面
【发布时间】:2014-12-01 11:17:50
【问题描述】:

函数Hmisc::escapeRegex 转义字符串中的任何特殊字符。

library(Hmisc)
string <- "this\\(system) {is} [full]."
escapeRegex(string)

它基于gsubregexp

escapestring <- gsub("([.|()\\^{}+$*?]|\\[|\\])", "\\\\\\1", string)
escapestring 
[1] "this\\\\\\(system\\) \\{is\\} \\[full\\]\\."

如何去除escapestring的反斜杠,以便找回原来的string

【问题讨论】:

  • 类似gsub("\\", "", x) 但这也会删除原始字符串中的任何`\`。
  • 这项任务最困难的部分将是识别 "\\(" 是原始的,因为 "(" 是一个正则表达式元字符。

标签: r regex escaping gsub


【解决方案1】:

您实际上只需要保留每个 \ 之后的字符即可取消转义。

string <- "this\\(system) {is} [full]."
library(Hmisc)
gsub("\\\\(.)", "\\1", escapeRegex(string))

#> [1] "this\\(system) {is} [full]."

或者rex 可以使转义和非转义都更简单一些。

library(rex)
re_substitutes(escape(string), rex("\\", capture(any)), "\\1", global = TRUE)

#> [1] "this\\(system) {is} [full]."

【讨论】:

    【解决方案2】:

    正则表达式怎么样

    \\\\([.|()\\^{}+$*?]|\\[|\\])
    

    替换为捕获组\1

    使用示例

    escapestring <- "this\\\\\\(system\\) \\{is\\} \\[full\\]\\."
    string <- gsub("\\\\([.|()\\^{}+$*?]|\\[|\\])", "\\1", escapestring)
    string
    [1] "this\\(system) {is} [full]."
    

    【讨论】:

    • (不反对)。您应该使用实际使用的内容更新上面的正则表达式,并且可以将 ][ 放在字符类中。
    • @nhahtdh 谢谢。我已经更新了我的正则表达式。我没有在字符类中包含[],因为我只是复制了操作使用的版本
    【解决方案3】:

    也许这也有帮助

    gsub("\\\\[(](*SKIP)(*F)|\\\\", '', escapestring, perl=TRUE)
    #[1] "this\\(system) {is} [full]."
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2014-04-09
      • 2013-07-25
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多