Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何匹配不在括号和引号中的文本?_Javascript_Regex - Fatal编程技术网

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

Javascript 如何匹配不在括号和引号中的文本?,javascript,regex,Javascript,Regex,我有这样一个字符串: this text (an another text) "and a text" and again a text 我想要的是只匹配第一个文本。另外两个text单词要么在括号内,要么在引号内 this text (an another text) "and a text" and again a text ^ this is I do want to capture. and this -> ^ 如何在单个正则表达式匹配中实现这一点?我无法在一

我有这样一个字符串:

this text (an another text) "and a text" and again a text
我想要的是只匹配第一个
文本
。另外两个
text
单词要么在括号内,要么在引号内

this text (an another text) "and a text" and again a text
      ^ this is I do want to capture.     and this -> ^
如何在单个正则表达式匹配中实现这一点?我无法在一次匹配中找到两种情况的任何解决方案

文本可以是任意顺序。

var sTest='此文本(另一个文本)”和一个文本“;

document.writeln(sTest.replace(/\([^)]*text[^)]*\)|“[^”]*text[^”]*”| text/g,(sMatch)=>{return(sMatch=='text'?'text':sMatch);})希望它匹配所有可能的组合。见结果

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

我知道您请求了一个正则表达式,但两个过程的可扩展性更强,更易于阅读和调试,而且性能也不会降低

也可以简单地添加更多的bookend类型

const input=`此文本(另一个文本)”和一个文本“更多文本”
(这是
文本
)
”“还有更多
“文本”
尾随文本(应该是第三个匹配的文本)
`
//删除所有匹配的(…)和“…”
const sanitized=input.replace(/\([^)]*\)|“[^”]*”/g',)
console.log(已消毒)
//现在匹配
设rx=/text/g
让我
设x=0
while(m=rx.exec(消毒)){
控制台日志(m)

}
你的意思是?它们可以按任何顺序排列吗?@Eric,是的,它们可以按任何顺序排列。@UnerableLightness让我试试……更新:它会选择所有文本,不管是什么。使用regexr应用程序进行了尝试。已经有可用的答案。你可以组合它们:我必须将此regex传递给另一个方法。因此,它不可能作为y进行筛选我也没有机会访问这部分代码:(你能把lamda传递给你的另一个函数而不是regex吗?不知道这对OP来说是不是一个问题,但是这个regex会失败,比如
(另一个文本))
“some(text)”
 ((?!(?:( (\(|")[a-zA-Z ]+(\)|") )))?([\w ]+)(?=(?:( (\(|")[a-zA-Z ]+(\)|" ))))|([\w ]+$))