javascript - Regex for something not between quotes and parenthesis
问题描述
I want to match the word hello
that is not between any type of quote (''
or ""
or ``
) and not in parentheses.
An example match would be:
'hello'(hello)('hello')hello
^^^^^ # the last hello is matched
If there is any way to do something like this I would appreciate it. Thanks!
What i have tried is this:
'(hello)+(?=(?:[^\'"`]*[\'"`][^\'"`]*[\'"`])*[^\'"`]*$)(?!\()(?<!\))'
but it always returns nothing as a match
I am trying to get the index of the match.
解决方案
正则表达式并不是真正的正确工具。此外,JavaScript(目前)不支持(?R)
-recursion 逻辑,因此为了支持嵌套括号检测,最好使用普通的旧for
循环。
这是一个完成这项工作的函数。它使用您提供的示例输入和单词运行,并返回找到良好匹配的索引——在本例中为 23:
function findOccurrence(input, word) {
for (let i = 0, j = -1, nesting = 0; i < input.length; i++) {
let ch = input[i];
if (i > j) {
j = input.indexOf(word, i); // find next occurrence of word
if (j < 0) return -1; // no more occurrences...
}
if (i === j && nesting === 0) return i; // bingo!
if ("`'\"".includes(ch)) { // opening quote
i = input.indexOf(ch, i+1); // jump to closing quote (of same type)
} else if (ch === "(") {
nesting++;
} else if (nesting > 0 && ch === ")") {
nesting--;
}
}
return -1; // not found
}
// example:
console.log(findOccurrence("'hello'(hello)('hello')hello", "hello"));
推荐阅读
- docker - 为什么我们在 Docker Compose 中增加版本?(版本 1、2 和 3)
- c++ - 我修改了 gtest/gmock,所以很容易模拟非虚拟函数
- gcc - STM32:ST-Link 尝试闪存 RAM 区域
- c# - 如何使用设置定义组?
- .net-core - 如何忽略或覆盖 .NET Core Web Api 中的请求标头?
- replace - 删除书签行时保留换行符
- java - 父级中的 getChildren 方法 - JavaFX
- ios - 处理缓存对吗?
- javascript - 如何在 Angular 6 中访问 IFrame DOM?
- javascript - 文件拦截器不起作用