【问题标题】:regex patterns on R: n-dash, m-dash, parenthesesR 上的正则表达式模式:n-dash、m-dash、括号
【发布时间】:2021-03-28 20:31:19
【问题描述】:

我有两个正则表达式问题:

第 1 部分: 我有一个带有这样字符串的字符向量:

raw_strings <- c("hello world (abc)", "no hi world (abc(d))")

我想提取第一组括号内的内容,像这样:

clean_strings <- c("abc", "abc(d)")

到目前为止,我一直在使用这个:

str_extract(raw_strings, "(?<=\\().+?(?=\\))")

但是,结果如下:

"abc" "abc(d"

如何更改表达式以保留最后的括号?

第 2 部分: 我有一些看起来像这样的字符串:

b_strings <- c("5.2 ko – word (longer word)", "5.9 ko - two words (long)")

我想要这个:

b_strings_clean <- c("word", "two words")

到目前为止,我已经这样做了:

str_extract(ac_meta, "\\s[^-–]*$")

结果:

"word (longer word)" "two words (long)"

如何删除括号后的所有内容(包括括号)?

谢谢。

【问题讨论】:

    标签: r regex string tidyverse


    【解决方案1】:

    使用环视是否有效:

    str_extract(raw_strings, '(?<=\\().*(?=\\))')
    [1] "abc"    "abc(d)"
    
    str_extract(b_strings, '(?<=[–-]\\s).*(?=\\s\\()')
    [1] "word"      "two words"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多