javascript 检查正则表达式是否适用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6390695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript check if regex apply
提问by YeppThat'sMe
First of all, here is my code snippet:
首先,这是我的代码片段:
var str = '<!--:de-->some german text<!--:--><!--:en-->some english text<!--:-->';
var match = str.match(/de-->([^<]+).+?en[^>]+>([^<]+)/i);
var textInDe = match[1];
var textInEn = match[2];
I've got this regex validation (thanks to The Mask) which works great.
我有这个正则表达式验证(感谢 The Mask),效果很好。
Now, I want to check with an if-statement if this regex applies to some string or not. I'm using Javascript jquery.
现在,我想使用 if 语句检查此正则表达式是否适用于某个字符串。我正在使用 Javascript jquery。
Thanks in advance :)
提前致谢 :)
回答by Dogbert
You can use RegExp.test
您可以使用RegExp.test
if(/de-->([^<]+).+?en[^>]+>([^<]+)/i.test(str)) {
// something
}
回答by Satyajit
var str = '<!--:de-->some german text<!--:--><!--:en-->some english text<!--:-->';
var match = str.match(/de-->([^<]+).+?en[^>]+>([^<]+)/i);
if(match.length > 0){
//successful match
}
OR
或者
var re = new RegExp('regex string');
if (somestring.match(re)) {
//successful match
}
回答by kheya
How about this?
这个怎么样?
function IsMatch(v) {
//basically build your regex here
var exp = new RegExp("^de-->([^<]+).+?en[^>]+>([^<]+)$"); return exp.test(v);
}
To call it:
if(IsMatch('Your string')) alert('Found'); else alert('Not Found');