验证正则表达式是否 Posix 兼容

Verify if a regex is Posix compatible

我想知道是否有一种方法可以使用 Java.

验证正则表达式是否 Posix 兼容

我正在使用 MySQL 5.7 版本和 "normal" 带有 REGEXP 函数的正则表达式:

MySQL uses Henry Spencer's implementation of regular expressions, which is aimed at conformance with POSIX 1003.2. MySQL uses the extended version to support regular expression pattern-matching operations in SQL statements.

如果我尝试使用其中的一些令牌,例如:

它们被认为无效或被 MySQL 忽略。可能还有其他的。

我知道 Java Pattern class 可用于验证正则表达式是否有效,使用:

Pattern.compile(regex);

如果正则表达式无效则返回异常。但是,正如我所说,我正在尝试验证正则表达式是否仅 Posix 兼容,因此我可以在将信息保存到数据库之前验证正则表达式输入。

Perl 兼容的正则表达式 (PCRE) 支持 \w\d(?:) 等语法,POSIX 不支持。 egrep 等工具支持增强的兼容性功能,但这并不能使它们成为 POSIX。

来自 re_format(7) 的手册页:

ENHANCED FEATURES

When the REG_ENHANCED flag is passed to one of the regcomp() variants, additional features are activated. Like the enhanced regex implementations in scripting languages such as perl(1) and python(1), these additional features may conflict with the IEEE Std 1003.2 (``POSIX.2'') standards in some ways. Use this with care in situations which require portability (including to past versions of the Mac OS X using the previous regex implementation).

"extended" 和 "enhanced." 之间有区别 扩展指的是 POSIX 正则表达式功能的级别。 Enhanced是指PCRE支持但POSIX.

不支持的语法

你可以在 POSIX 语法中做很多你想做的事情:

  • 对于\w,使用[[:alnum:]_]

  • 对于\d,使用[[:digit:]]

  • (?:) 语法是不必要的,因为 MySQL REGEXP 无论如何都不支持捕获组。您可以简单地使用 () 进行分组。

我认为没有必要使用 Java 验证器来解析您的正则表达式。您应该能够阅读文档并仅使用该文档中出现的功能。

我的意思是,真的,正则表达式语法并不那么复杂。您可以在 Post-It 注释上创建一个快速参考 sheet。