【问题标题】:R: How to match regex but not substringR:如何匹配正则表达式而不是子字符串
【发布时间】:2014-12-31 10:11:56
【问题描述】:

我有正则表达式字符串数据,但想排除子字符串

dat <- c('long_regex_other_stuff','long_regex_other_random.something')
(dat[grep('long_regex',dat)])
(dat[grep('long_regex.*(?!.*something$)',dat)])

第一个 grep 输出是预期的

"long_regex_other_stuff"            "long_regex_other_random.something"

如何让第二个 grep 工作?所需的输出是

"long_regex_other_stuff"

参考:Regular expression to match a line that doesn't contain a word?

【问题讨论】:

    标签: regex r substring


    【解决方案1】:

    你需要把正则表达式中字符串something前面的.*去掉,加在负前瞻后面,

    > dat <- c('long_regex','long_regex.something')
    > (dat[grep('long_regex(?!.*something).*',dat, perl=T)])
    [1] "long_regex"
    > (dat[grep('long_regex(?!.*\\bsomething\\b).*',dat, perl=T)])
    [1] "long_regex"
    

    long_regex(?!.*something) 此正则表达式中存在的负前瞻断言在子字符串 long_regex 之后不存在字符串 something

    > dat <- c('long_regex_other_stuff','long_regex_other_random.something')
    > (dat[grep('long_regex(?!.*\\bsomething\\b).*',dat, perl=T)])
    [1] "long_regex_other_stuff"
    

    【讨论】:

    • 让我在“实际”数据上检查这个答案...这不太行,我将更改示例...
    • 你能解释一下原因吗?因此,我们可以提供一个准确的答案。
    • long_regex 和 ".something" 之间有随机字符,原始示例中没有
    • 当我将它应用于数据时,我收到错误“原因'无效的正则表达式'”。给我几分钟来更新示例(再次)或更正应用程序...
    • 我不知道它如何给出无效的正则表达式。您是否复制了我提供的确切正则表达式?你启用perl=TRUE参数了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 2011-11-08
    • 2013-04-13
    • 2022-07-11
    • 1970-01-01
    相关资源
    最近更新 更多