JavaScript和正则表达式:文字语法Vs. RegExp对象 [英] JavaScript and regular expressions: literal syntax Vs. RegExp object
本文介绍了JavaScript和正则表达式:文字语法Vs. RegExp对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对这个小的JavaScript代码有些麻烦:
I have some troubles with this small JavaScript code:
var text="Z Test Yeah ! Z";
// With literal syntax, it returns true: good!
alert(/(Z[\s\S]*?Z)/g.test(text));
// But not with the RegExp object O_o
var reg=new RegExp('Z[\s\S]*?Z','g');
alert(reg.test(text));
我不明白为什么文字语法和RegExp对象不能给我相同的结果...
问题是我必须使用RegExp对象,因为我稍后会有一些变量。
I don't understand why the literal syntax and the RegExp object don't give me the same result... The problem is that I have to use the RegExp object since I'll have some variables later.
任何想法?
提前致谢:)
推荐答案
你需要双重逃避 \
字符串文字中的字符,这就是通常首选正则表达式文字的原因。
You need to double escape \
characters in string literals, which is why the regex literal is typically preferred.
尝试:
'Z[\\s\\S]*?Z'
这篇关于JavaScript和正则表达式:文字语法Vs. RegExp对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文