如何匹配不在括号和引号中的文本?

时间:2018-07-28 13:59:29

标签: javascript regex

我有一个像这样的字符串:

text

我要只匹配第一个text。其他两个this text (an another text) "and a text" and again a text ^ this is I do want to capture. and this -> ^ 单词要么在括号内,要么在引号中。

del sns_plot, x_list, y_list

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

文本可以是任何顺序。

3 个答案:

答案 0 :(得分:2)

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。 首先定义您不想包含的内容,然后剩下的只有您想要的内容。

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

我知道您要求使用单个正则表达式,但是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)
}