0

I'm looking to have the (admin) user enter some pattern matching string, to give different users of my website access to different database rows, depending on if the text in a particular field of the row matches the pattern matching string against that user.

I decided on Regex because it is trivial to integrate into the MySQL statements directly.

I don't really know where to start with validating that a string is a valid regular expression, with a regular expression.

I did some searching for similar questions, couldn't see one. Google produced the comical answer, sadly not so helpful.

Do people do this in the wild, or avoid it?

Is it able to be done with a simple regex, or will the set of all valid regex need to be limited to a usable subset?

4

3 回答 3

2

在 JavaScript 中:

input = "hello**";

try{
        RegExp(input);
        // sumbit the regex
}catch(err){
        // regex is not valid
}
于 2012-12-18T15:37:33.507 回答
2

验证正则表达式是一项极其复杂的任务。正则表达式将无法做到这一点。

一种简单的方法是捕获尝试运行 SQL 语句时发生的任何错误,然后将适当的错误报告给用户。

我假设“管理员”是这里的受信任用户。让不受信任的用户能够输入正则表达式是非常危险的,因为使用构造为需要很长时间才能执行的正则表达式很容易攻击您的系统。那是在您开始担心Bobby Tables问题之前。

于 2012-12-18T15:22:46.420 回答
-1

您无法使用正则表达式验证字符串是否包含有效的正则表达式。但你也许可以妥协。

如果您只需要知道字符串中仅使用了正则表达式中有效的字符,则可以使用正则表达式:

^[\d\w \-\}\{\)\(\+\*\?\|\.\$\^\[\]\\]*$

这可能就足够了,具体取决于应用程序。

于 2012-12-19T08:39:18.803 回答