Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

javascript - 正则表达式语法错误(Regular Expression Syntax Error)

I am creating a regex dynamically.(我正在动态创建一个正则表达式。)

  var link = "www.google.com"; var reg = '^'+link+'{1}|(?<=\s)'+link+'{1}(?=\s)|'+link+'{1}$'; console.log(reg); var result = new RegExp(reg, 'g'); 

I am getting this error(我收到此错误)

Uncaught SyntaxError: Invalid regular expression: /^www.google.com{1}|(?<=s)www.google.com{1}(?=s)|www.google.com{1}$/: Invalid group

Here is the generated regex:(这是生成的正则表达式:)

^www.google.com{1}|(?<=s)www.google.com{1}(?=s)|www.google.com{1}$

  ask by user3816152 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JavaScript regex engine did not support look-behinds at all before ECMAScript 2018 was released.(JavaScript的正则表达式引擎根本不支持查找屁股的ECMAScript 2018发布之前。)

Now, if you use this in Chrome, it will not throw any error now:(现在,如果您在Chrome中使用此功能,它将不会引发任何错误:)

 var link = "www.google.com"; var reg = '^'+link+'{1}|(?<=\s)'+link+'{1}(?=\s)|'+link+'{1}$'; console.log(reg); var result = new RegExp(reg, 'g'); 

Another thing: you must double escape \ inside RegExp constructor.(另一件事:您必须在RegExp构造函数中加倍转义\ 。)

What you are trying to acheive is to make the URL match at word boundaries.(您要达到的目的是使URL在单词边界处匹配。)

Try using(尝试使用)

RegExp.escape= function(s) {
    return s.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');
};

var reg = '\b'+RegExp.escape(link)+'\b';

Code:(码:)

 RegExp.escape= function(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }; var link = "www.google.com" var reg = '\\b'+RegExp.escape(link)+'\\b'; alert(new RegExp(reg, "g")); 

Note I am adding the RegExp.Escape in order to escape special characters in the arguments passed to the RegExp constructor (eg . must be \\. ).(注意,我正在添加RegExp.Escape以便在传递给RegExp构造函数的参数中转义特殊字符(例如.必须为\\. )。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...