如何验证正则表达式? [英] How can I validate regex?
问题描述
我想在PHP中测试正则表达式的有效性,最好在使用前进行测试.这样做的唯一方法是实际尝试preg_match()
并查看它是否返回FALSE
吗?
I'd like to test the validity of a regular expression in PHP, preferably before it's used. Is the only way to do this actually trying a preg_match()
and seeing if it returns FALSE
?
是否有更简单/正确的方法来测试有效的正则表达式?
Is there a simpler/proper way to test for a valid regular expression?
推荐答案
// This is valid, both opening ( and closing )
var_dump(preg_match('~Valid(Regular)Expression~', null) === false);
// This is invalid, no opening ( for the closing )
var_dump(preg_match('~InvalidRegular)Expression~', null) === false);
正如用户 pozs 所说,还考虑在测试环境中将@
放在preg_match()(@preg_match()
)前面,以防止发出警告或通知.
As the user pozs said, also consider putting @
in front of preg_match() (@preg_match()
) in a testing environment to prevent warnings or notices.
要验证RegExp,只需针对null
(无需知道您要预先测试的数据)运行它即可..如果返回显式false(=== false
),则表示它已损坏.否则它是有效的,尽管它不需要匹配任何内容.
To validate a RegExp just run it against null
(no need to know the data you want to test against upfront). If it returns explicit false (=== false
), it's broken. Otherwise it's valid though it need not match anything.
因此无需编写自己的RegExp验证器. 这是浪费时间...
这篇关于如何验证正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!