正则表达式错误

Regular Expression Error

本文关键字:错误 正则表达式      更新时间:2023-09-26

下面是我正在使用的正则表达式的最新版本,它抛出错误"无效的正则表达式"。

任何带有正则表达式格式的 foo 将不胜感激!

下面是我的代码:

// This function gets all the text in browser
function getText() {
    return document.body.innerText;
}
var allText = getText(); // stores into browser text into variable
//regex set to rid text of all punctuaction, symbols, numbers, and excess  spaces
var matcher = new RegExp ("/(?<!'w)[a-zA-Z]+(?!'w)/", "g");
//cleanses text in browser of punctuation, symbols, numbers, and excess spaces
var newWords = allText.match(matcher);
//using a single space as the dividing tool, creates a list of all words
var Words=newWords.split(" ");

而不是

//regex set to rid text of all punctuaction, symbols, numbers, and excess  spaces
var matcher = new RegExp ("/(?<!'w)[a-zA-Z]+(?!'w)/", "g");
//cleanses text in browser of punctuation, symbols, numbers, and excess spaces
var newWords = allText.match(matcher);
//using a single space as the dividing tool, creates a list of all words
var Words=newWords.split(" ");

只需使用

var Words = allText.match(/'b[a-zA-Z]+'b/g); // OR...
// var Words = allText.match(/'b[A-Z]+'b/ig);

这将为您提供所有仅由 ASCII 字母组成的"单词",因为String#match与基于 /g 的正则表达式一起获取与正则表达式匹配的所有子字符串(匹配单词边界之间的 1 个或多个 ASCII 字母)。

JS不支持回溯(即 (?<!)(?<=)结构),您需要在此处'b单词边界。

请注意,您需要类似 .replace(/'W+/g, ' ') 的东西来删除文本中的所有标点符号、符号、数字和多余的空格,但似乎您可以依靠 .match(/'b[a-zA-Z]'b/g) .