如何检查输入字符串是否为有效的正则表达式? [英] How to check if the input string is a valid Regular expression?

查看:43
本文介绍了如何检查输入字符串是否为有效的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JavaScript中检查字符串是否是可以编译的正确正则表达式?

How do you check, in JavaScript, if a string is a proper regular expression that will compile?

例如,当您执行以下javascript时,会产生错误.

For example, when you execute the following javascript, it produces an error.

var regex = new RegExp('abc ([a-z]+) ([a-z]+))');
// produces:
// Uncaught SyntaxError: Invalid regular expression: /abc ([a-z]+) ([a-z]+))/: Unmatched ')'

如何确定字符串是否为有效的正则表达式?

How does one determine if a string will be a valid regex or not?

推荐答案

您可以使用 try/catch RegExp 构造函数:

You can use try/catch and the RegExp constructor:

var isValid = true;
try {
    new RegExp("the_regex_to_test_goes_here");
} catch(e) {
    isValid = false;
}

if(!isValid) alert("Invalid regular expression");

这篇关于如何检查输入字符串是否为有效的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆