정규식의 유효성을 어떻게 확인할 수 있습니까?
가급적 사용하기 전에 PHP에서 정규 표현식의 유효성을 테스트하고 싶습니다. 이 작업을 수행하는 유일한 방법은 실제로 a를 시도하고 preg_match()
반환되는지 확인하는 것 FALSE
입니까?
유효한 정규식을 테스트하는 더 간단하고 적절한 방법이 있습니까?
// 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()
.
RegExp의 유효성을 검사하려면이를 실행하기 만하면됩니다 null
(사전에 대해 테스트 할 데이터를 알 필요가 없음) . 명시 적 false ( === false
)를 반환하면 고장난 것입니다. 그렇지 않으면 아무것도 일치하지 않아도 유효합니다.
따라서 자신의 RegExp 유효성 검사기를 작성할 필요가 없습니다. 시간 낭비 ...
프리그 검사에 호출 할 수있는 간단한 함수를 만들었습니다.
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()];
}
다음 코드를 사용하여이 함수를 호출 할 수 있습니다.
preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');
echo is_preg_error();
대안-정규식 온라인 테스터
동적으로 테스트하려는 경우 정규식 preg_match(...) === false
이 유일한 옵션 인 것 같습니다. PHP에는 정규식을 사용하기 전에 컴파일하는 메커니즘이 없습니다.
또한 preg_last_error 가 유용한 기능 임을 알 수 있습니다.
반면에 정규식이 있고 사용하기 전에 유효한지 알고 싶다면 사용할 수있는 도구가 많이 있습니다. 나는 rubular.com이 사용 하기 즐겁다 는 것을 알았 습니다.
엔진이 재귀를 지원한다면 (PHP가해야하는 경우) 정규식의 악몽으로 구문 상 올바른 정규식인지 확인할 수 있습니다.
그러나 실행하지 않고 원하는 결과를 얻을 수 있는지 알고리즘 적으로 알 수는 없습니다.
From : 유효한 정규식을 감지하는 정규식이 있습니까?
/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/
실제로 정규식을 실행하지 않으면 유효한지 확인할 방법이 없습니다. 최근에 Zend Framework에 대해 유사한 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;
}
}
당신은 당신의 정규 표현식을 검증 할 수 있습니다 정규 표현식 및 특정 한도까지 . 자세한 내용은 이 스택 오버플로 답변 을 확인하십시오.
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
So in summary, for all those coming to this question you can validate regular expressions in PHP with a function like this.
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred. - PHP Manual
/**
* 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);
}
I am not sure if it supports PCRE, but there is a Chrome extension over at https://chrome.google.com/webstore/detail/cmmblmkfaijaadfjapjddbeaoffeccib called RegExp Tester. I have not used it as yet myself so I cannot vouch for it, but perhaps it could be of use?
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.
The answer to this question has a great answer on setting up your unit tests.
You should try to match the regular expression against NULL
. If the result is FALSE (=== FALSE
), there was an error.
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:
preg_match($regex, NULL);
echo array_flip(get_defined_constants(true)['pcre'])[preg_last_error()];
According to the PCRE reference, there is no such way to test validity of an expression, before it's used. But i think, if someone use an invalid expression, it's a design error in that application, not a run-time one, so you should be fine.
참고URL : https://stackoverflow.com/questions/4440626/how-can-i-validate-regex
'Nice programing' 카테고리의 다른 글
Golang에서 http 연결 재사용 (0) | 2020.11.16 |
---|---|
mongodb 컬렉션에서 최대 가치를 얻는 방법 (0) | 2020.11.16 |
구성 변환을 사용하여 ConnectionString을 제거하는 방법 (0) | 2020.11.16 |
div 내에서 두 줄로만 텍스트 감싸기 (0) | 2020.11.16 |
strcpy 대 strdup (0) | 2020.11.16 |