如何在javascript中使用正则表达式?
我在regexlib中找到了一个正则表达式,我想用javascript在一个简单的字符串验证中使用它 正则表达式是:如何在javascript中使用正则表达式?,javascript,Javascript,我在regexlib中找到了一个正则表达式,我想用javascript在一个简单的字符串验证中使用它 正则表达式是: ^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$ 但我试着这样使用它: mystring = 'hello@world.com'; re = '^([a-zA-Z0-9_\-\.]+)@((\[
^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$
但我试着这样使用它:
mystring = 'hello@world.com';
re = '^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$';
if(mystring.match(re)){
console.log('true');
}
var re = new RegExp('^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');
我得到了这个控制台错误:
Uncaught SyntaxError: Invalid regular expression: //^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$/: Range out of order in character class
怎么了?
我不是专业人士。。这只是我在空闲时间尝试做的一个简单项目。试着这样做:
mystring = 'hello@world.com';
re = '^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$';
if(mystring.match(re)){
console.log('true');
}
var re = new RegExp('^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');
在javascript中,\
字符转义字符串,因此它不起作用。在上一个例子中,我只是将它们加倍,这应该是可行的。在实践中:
mystring='1〕hello@world.com';
re=新的正则表达式('^([a-zA-Z0-9\\-\\\\\.]+)@(\[[0-9]{1,3}\.[0-9]{1,3}\\.[0-9]{1,3}\\\\.)([a-zA-Z0-9\\\-]+\\.+)([a-zA-Z]{2,4}.[0-9]{1,3}.$);
if(mystring.match(re)){
console.log('true');
}
试着这样做:
mystring = 'hello@world.com';
re = '^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$';
if(mystring.match(re)){
console.log('true');
}
var re = new RegExp('^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');
在javascript中,\
字符转义字符串,因此它不起作用。在上一个例子中,我只是将它们加倍,这应该是可行的。在实践中:
mystring='1〕hello@world.com';
re=新的正则表达式('^([a-zA-Z0-9\\-\\\\\.]+)@(\[[0-9]{1,3}\.[0-9]{1,3}\\.[0-9]{1,3}\\\\.)([a-zA-Z0-9\\\-]+\\.+)([a-zA-Z]{2,4}.[0-9]{1,3}.$);
if(mystring.match(re)){
console.log('true');
}
要定义正则表达式,您需要使用/
而不是'
mystring='1〕hello@world.com';
re=/^([a-zA-Z0-9\-\.]+)(\[[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.\)(([a-zA-Z0-9\-]+)([a-zA-Z]{2,4}.[0-9]{1,3}.))(\]?)$/;
if(mystring.match(re)){
console.log('true');
}
要定义正则表达式,您需要使用/
而不是'
mystring='1〕hello@world.com';
re=/^([a-zA-Z0-9\-\.]+)(\[[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.\)(([a-zA-Z0-9\-]+)([a-zA-Z]{2,4}.[0-9]{1,3}.))(\]?)$/;
if(mystring.match(re)){
console.log('true');
}
当我尝试遵循此另一个post解决方案时,可能重复出现另一个错误:未捕获的语法错误:无效或意外标记当我尝试遵循此另一个post解决方案时,可能重复出现另一个错误:未捕获的语法错误:无效或意外标记