php 如何验证正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4440626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I validate regex?
提问by Ross McFarlane
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
?
我想在 PHP 中测试正则表达式的有效性,最好是在使用之前。这样做的唯一方法是实际尝试 apreg_match()
并查看它是否返回FALSE
?
Is there a simpler/proper way to test for a valid regular expression?
是否有更简单/正确的方法来测试有效的正则表达式?
回答by CodeAngry
// 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);
As the user pozssaid, also consider putting @
in front of preg_match()(@preg_match()
) in a testing environment to prevent warnings or notices.
正如用户pozs所说,在测试环境中还要考虑@
在preg_match()( @preg_match()
)前面放置,以防止出现警告或通知。
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 只需针对它运行它null
(无需预先知道要针对哪些数据进行测试)。如果它返回显式 false ( === false
),则它已损坏。否则它是有效的,尽管它不需要匹配任何东西。
So there's no need to write your own RegExp validator.It's wasted time...
所以没有必要编写自己的 RegExp 验证器。真是浪费时间...
回答by Wahyu Kristianto
I created a simple function that can be called to checking preg
我创建了一个简单的函数,可以调用它来检查 preg
function is_preg_error()
{
$errors = array(
PREG_NO_ERROR => 'Code 0 : No errors',
PREG_INTERNAL_ERROR => 'Code 1 : There was an internal PCRE error',
PREG_BACKTRACK_LIMIT_ERROR => 'Code 2 : Backtrack limit was exhausted',
PREG_RECURSION_LIMIT_ERROR => 'Code 3 : Recursion limit was exhausted',
PREG_BAD_UTF8_ERROR => 'Code 4 : The offset didn\'t correspond to the begin of a valid UTF-8 code point',
PREG_BAD_UTF8_OFFSET_ERROR => 'Code 5 : Malformed UTF-8 data',
);
return $errors[preg_last_error()];
}
You can call this function using the follow code :
您可以使用以下代码调用此函数:
preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');
echo is_preg_error();
Alternative - Regular Expression Online Tester
替代 - 正则表达式在线测试器
回答by Alin Purcaru
If you want to dynamically test a regex preg_match(...) === false
seems to be your only option. PHP doesn't have a mechanism for compiling regular expressions before they are used.
如果您想动态测试正则表达式preg_match(...) === false
似乎是您唯一的选择。PHP 没有在使用前编译正则表达式的机制。
Also you may find preg_last_erroran useful function.
此外,您可能会发现preg_last_error是一个有用的函数。
On the other hand if you have a regex and just want to know if it's valid before using it there are a bunch of tools available out there. I found rubular.comto be pleasant to use.
另一方面,如果您有一个正则表达式并且只想在使用它之前知道它是否有效,那么有很多工具可用。我发现rubular.com 使用起来很愉快。
回答by evandentremont
You can check to see if it is a syntactically correct regex with this nightmare of a regex, if your engine supports recursion (PHP should).
如果您的引擎支持递归(PHP 应该支持),您可以使用正则表达式的噩梦来检查它是否是语法正确的正则表达式。
You cannot, however algorithmically tell if it will give the results you want without running it.
但是,您无法通过算法判断它是否会在不运行的情况下给出您想要的结果。
From: Is there a regular expression to detect a valid regular expression?
/^((?:(?:[^?+*{}()[\]\|]+|\.|\[(?:\^?\.|\^[^\]|[^\^])(?:[^\]\]+|\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/
回答by ChrisR
Without actually executing the regex you have no way to be sure if it's be valid. I've recently implemented a similar RegexValidator for Zend Framework. Works just fine.
如果不实际执行正则表达式,您就无法确定它是否有效。我最近为 Zend 框架实现了一个类似的 RegexValidator。工作得很好。
<?php
class Nuke_Validate_RegEx extends Zend_Validate_Abstract
{
/**
* Error constant
*/
const ERROR_INVALID_REGEX = 'invalidRegex';
/**
* Error messages
* @var array
*/
protected $_messageTemplates = array(
self::ERROR_INVALID_REGEX => "This is a regular expression PHP cannot parse.");
/**
* Runs the actual validation
* @param string $pattern The regular expression we are testing
* @return bool
*/
public function isValid($pattern)
{
if (@preg_match($pattern, "Lorem ipsum") === false) {
$this->_error(self::ERROR_INVALID_REGEX);
return false;
}
return true;
}
}
回答by rajukoyilandy
You can validate your regular expression with a regular expressionand up to a certain limit. Checkout this stack overflow answerfor more info.
您可以使用正则表达式验证您的正则表达式并达到一定的限制。查看此堆栈溢出答案以获取更多信息。
Note: a "recursive regular expression" is not a regular expression, and this extended version of regex doesn't match extended regexes.
注意:“递归正则表达式”不是正则表达式,并且此正则表达式的扩展版本与扩展的正则表达式不匹配。
A better option is to use preg_match
and match against NULL as @Claudrian said
更好的选择是preg_match
像@Claudrian所说的那样使用和匹配 NULL
回答by Xeoncross
So in summary, for all those coming to this question you can validate regular expressions in PHP with a function like this.
总而言之,对于所有遇到此问题的人,您可以使用这样的函数验证 PHP 中的正则表达式。
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred. - PHP Manual
如果模式匹配给定主题,则 preg_match() 返回 1,如果不匹配则返回 0,如果发生错误则返回 FALSE。- PHP 手册
/**
* Return an error message if the regular expression is invalid
*
* @param string $regex string to validate
* @return string
*/
function invalidRegex($regex)
{
if(preg_match($regex, null) !== false)
{
return '';
}
$errors = array(
PREG_NO_ERROR => 'Code 0 : No errors',
PREG_INTERNAL_ERROR => 'Code 1 : There was an internal PCRE error',
PREG_BACKTRACK_LIMIT_ERROR => 'Code 2 : Backtrack limit was exhausted',
PREG_RECURSION_LIMIT_ERROR => 'Code 3 : Recursion limit was exhausted',
PREG_BAD_UTF8_ERROR => 'Code 4 : The offset didn\'t correspond to the begin of a valid UTF-8 code point',
PREG_BAD_UTF8_OFFSET_ERROR => 'Code 5 : Malformed UTF-8 data',
);
return $errors[preg_last_error()];
}
Which can be used like this.
可以这样使用。
if($error = invalidRegex('/foo//'))
{
die($error);
}
回答by Tash Pemhiwa
I am not sure if it supports PCRE, but there is a Chrome extension over at https://chrome.google.com/webstore/detail/cmmblmkfaijaadfjapjddbeaoffeccibcalled RegExp Tester. I have not used it as yet myself so I cannot vouch for it, but perhaps it could be of use?
我不确定它是否支持 PCRE,但在https://chrome.google.com/webstore/detail/cmmblmkfaijaadfjapjddbeaoffeccib 上有一个 Chrome 扩展名为RegExp Tester。我自己还没有使用过它,所以我不能保证它,但也许它可能有用?
回答by mbomb007
You should try to match the regular expression against NULL
. If the result is FALSE (=== FALSE
), there was an error.
您应该尝试将正则表达式与NULL
. 如果结果为 FALSE ( === FALSE
),则存在错误。
In PHP >= 5.5, you can use the following to automatically get the built-in error message, without needing to define your own function to get it:
在PHP>=5.5中,可以使用以下方式自动获取内置错误信息,无需自己定义函数获取:
preg_match($regex, NULL);
echo array_flip(get_defined_constants(true)['pcre'])[preg_last_error()];
回答by Rob Forrest
I'd be inclined to set up a number of unit tests for your regex. This way not only would you be able to ensure that the regex is indeed valid but also effective at matching.
我倾向于为您的正则表达式设置一些单元测试。通过这种方式,您不仅可以确保正则表达式确实有效,而且还可以有效匹配。
I find using TDD is an effective way to develop regex and means that extending it in the future is simplified as you already have all of your test cases available.
我发现使用 TDD 是一种开发正则表达式的有效方法,这意味着将来扩展它会很简单,因为您已经拥有所有可用的测试用例。
The answer to this questionhas a great answer on setting up your unit tests.
在回答这个问题,有关于设置的单元测试一个伟大的答案。