为什么正则表达式构造函数不起作用? [英] why is regex constructor not working?
本文介绍了为什么正则表达式构造函数不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在回答一个问题,以下内容返回 false
I was answering a question, and the following returns false
var regexp = new RegExp("([\w\.-]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})");
var result = regexp.test( $("#email").val() ); // returns false
而
var regexp = /([\w\.-]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/;
var result = regexp.test( $("#email").val() ); // returns true
那是为什么?
推荐答案
使用 RegExp
构造函数时,您需要转义 \
.
You need to escape \
when you use RegExp
constructor function.
new RegExp("([\\w\\.-]+)@((?:[\\w]+\\.)+)([a-zA-Z]{2,4})");
Quoting from MDN's RegExp
constructor Docs,
使用构造函数时,必须使用常规的字符串转义规则(当包含在字符串中时,在特殊字符前加上\).例如,以下是等效的:
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp("\\w+");
这篇关于为什么正则表达式构造函数不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文