如何在javascript中验证正则表达式

How to validate a regex expression in javascript?

本文关键字:验证 正则表达式 javascript      更新时间:2023-09-26

我有一个用户表单,它让用户能够输入正则表达式并提交到服务器。这些正则表达式的服务器端验证存在于现有用户,但我需要javascript正则表达式验证,以便在用户完成输入正则表达式后立即提示用户。

一些例子regex:

(.*?)_(.*?)_.*_(INS|UPD|DEL|UPSERT)$    -- CORRECT
^Schedule_(.a*)                         -- CORRECT
(IP(.*?)_(.*?)_.*_(INS|UPD|DEL|UPSERT)$ -- WRONG

注意: Regex将运行在服务器端(Elasticsearch)

使用try/catchRegExp构造函数,您可以跟踪Regex是否有效。请查看下面的代码片段以获得更多的理解。

var isValid = true;
try {
  new RegExp("(.*?)_(.*?)_.*_(INS|UPD|DEL|UPSERT)$");
} catch(e) {
  isValid = false;
}
if(!isValid) alert("This is invalid regular expression");
else alert("This is valid regular expression");