【问题标题】:Can't escape $ in regex using stringr::string_extract [duplicate]无法使用 stringr::string_extract 在正则表达式中转义 $ [重复]
【发布时间】:2020-11-15 00:26:26
【问题描述】:

在字符串中,我试图提取0.4% 之后的12 month(s)\n$500

我搜索12 month(s)\n$500,然后获取后面的数字点号。

来自here,“要匹配文字“$”或“^”,您需要对它们、$ 和^ 进行转义。” 但是当我这样做时,我得到了错误:

Error: '\$' is an unrecognized escape in character string starting ""(?<=12 month(s)\\n\$"

我做错了什么?

x <- "Term Minimum investment Rate Interest type Get this GIC\n3 month(s)\n$500 0.15% Simple\nChoose this GIC\n6 month(s)\n$500 0.25% Simple\nChoose this GIC\n9 month(s)\n$500 0.30% Simple\nChoose this GIC\n12 month(s)\n$500 0.40% Simple\nChoose this GIC\n18 month(s)\n$500 0.50% Simple\nChoose this GIC\n18 month(s)\n$500 0.50% Compound\nChoose this GIC"

as.numeric(stringr::str_extract(x, "(?<=12 month(s)\\n\$500)\\d\\.\\d{1,}"))

【问题讨论】:

    标签: r regex


    【解决方案1】:

    您需要在 R 中使用双反斜杠转义。(\\)。您还需要转义打开和关闭圆括号 (())。

    as.numeric(stringr::str_extract(x,"(?<=12 month\\(s\\)\n\\$500\\s)\\d\\.\\d{1,}"))
    #[1] 0.4
    

    在带有 sub 的基础 R 中:

    as.numeric(sub('.*12 month\\(s\\)\n\\$500\\s(\\d\\.\\d{1,}).*', '\\1', x))
    

    【讨论】:

    • 虽然我的问题是基本的,但我认为我会搜索版主的建议是不合理的。我忘记了括号需要转义。感谢@Ronak Shah 的快速响应。
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2021-09-17
    • 2018-09-06
    • 2017-05-06
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多