我需要找到一个可以在其中任意位置包含另一个固定模式的模式。
示例:
Looking for pattern: "HERE"
This pattern can also have one or multiple times the pattern "##" in it.
以下条目应匹配:
"A match is expected HE##RE"
"... also H##ER##E ..."
"... and the basic one HERE ..."
我试图做一个预计算的东西来删除这些不需要的“##”,但这是 Not Acceptable ,因为一些信息可能会丢失,就像这个例子中的那样:
"This is important ##and the match is only HER##E"
我还考虑过在预过滤计算之前为所有 ## 建立索引,然后用索引重建所有内容,但我认为这不是最佳解决方案。
有没有人有一些关于正则表达式的技巧或想法?
谢谢大家。
最佳答案
您可以使用可选组 (?:##)?
并使用单词边界 \b
来防止匹配成为更大单词的一部分:
\bH(?:##)?E(?:##)?R(?:##)?E\b
动态生成的一个选项可能是使用拆分和连接:
let d = "(?:##)?";
let word = "\\b" + "HERE".split('').join(d) + "\\b";
let str = "A match is expected HE##RE";
let pattern = new RegExp(word, 'gi');
console.log(pattern);
console.log(str.match(pattern));
关于javascript - 正则表达式模式在另一个模式中的任何地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57097027/