Regex不符合预期[重复]

ldioqlga  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(148)

此问题在此处已有答案

Escape string for use in Javascript regex [duplicate](1个答案)
2天前关闭。
在我的网页中,我有一个“查找”功能,用户在“查找”对话框中键入一些文本,它会获得在变量中可以找到文本的索引。事先我既不知道要搜索的文本,也不知道用户要查找的文本。我为他们提供了一个选项,以确定是否匹配大小写,以及是否仅查找整个单词(例如,如果他们输入“manager”,则“manager”是否应该匹配。
下面的代码是我的代码的精简版本,只包含了与我的问题相关的内容。在这个例子中,我想在“This is a test.(10)"中查找“(1)”。我期望在执行后索引将是-1,但它是16,这是“1”的索引。
你能告诉我为什么这个不起作用,什么会起作用?谢谢。

let matchCase = false;
    let wholeWord = false;
    let index = 0;
    let options = "";
    let phrase = "(1)";
    phrase = phrase.replaceAll(String.fromCharCode(160), "\\s");
    if (!matchCase) options += "i";
    if (wholeWord) phrase = "\\b" + phrase + "\\b";
    let regex = new RegExp(phrase, options);
    let text = "This is a test.(10)";
    let index = text.search(regex);
    console.log(index);
w8biq8rn

w8biq8rn1#

您需要在输入中转义正则表达式元字符,如(

//Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
let matchCase = false;
let wholeWord = false;
let options = "";
let phrase = escapeRegExp("(1)");
phrase = phrase.replaceAll(String.fromCharCode(160), "\\s");
if (!matchCase) options += "i";
if (wholeWord) phrase = "\\b" + phrase + "\\b";
let regex = new RegExp(phrase, options);
let text = "This is a test.(10)";
let index = text.search(regex);
console.log(index);

相关问题