【问题标题】:how to match text NOT in parentheses and quotes?如何匹配不在括号和引号中的文本?
【发布时间】:2018-07-28 13:59:28
【问题描述】:

我有一个这样的字符串:

this text (an another text) "and a text" and again a text

我想要的是只匹配第一个text。其他两个 text 单词要么在括号内,要么在引号中。

this text (an another text) "and a text" and again a text
      ^ this is I do want to capture.     and this -> ^

如何在单个正则表达式匹配中做到这一点?我无法在一次比赛中为这两种情况找到任何解决方案。

文本可以是任意顺序。

【问题讨论】:

标签: javascript regex


【解决方案1】:

var sTest = 'this text (an another text) "and a text"';
document.writeln(sTest.replace(/\([^)]*text[^)]*\)|"[^"]*text[^"]*"|text/g, (sMatch)=>{ return (sMatch === 'text' ? 'TEXT' : sMatch); }));

使用The Best Regex Trick。 你先定义你不想包含的东西,然后剩下的就是你想要的。

【讨论】:

    【解决方案2】:

    希望它能匹配所有可能的组合。查看结果here

     ((?!(?:( (\(|")[a-zA-Z ]+(\)|") )))?([\w ]+)(?=(?:( (\(|")[a-zA-Z ]+(\)|" ))))|([\w ]+$))
    

    它可能需要一些调整,但我相信这是一个好的开始。

    【讨论】:

    • 不知道这是否是 OP 的问题,但是对于 (an another text (text)) 或 "some (text)" 之类的东西,这个正则表达式会失败
    【解决方案3】:

    我知道您要求单个正则表达式,但是 2 次传递的可扩展性更高,更易于阅读和调试,而且性能也不低。

    也可以简单地添加更多书挡类型。

    const input = `this text (an another text) "and a text" more text
    
      ( this is
        text
       )
       
      " and more
        text"
        
     trailing text (should be the third text match)
    
    `
    
    // remove all matching (...) and "..."
    const sanitized = input.replace(/\([^)]*\)|"[^"]*"/g, '')
    console.log(sanitized)
    
    // now match
    let rx = /text/g
    let m
    let x = 0
    while (m = rx.exec(sanitized)) {
      console.log(m)
    }

    【讨论】:

    • 我必须将此正则表达式传递给另一个方法。因此,无法像您上面所说的那样进行过滤。而且我也没有机会访问那部分代码:(
    • 你能把 lamda 传递给你的其他函数而不是正则表达式吗?
    猜你喜欢
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    相关资源
    最近更新 更多