Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a string is regex

Is there a good way of test if a string is a regex or normal string in PHP?

Ideally I want to write a function to run a string through, that returns true or false.

I had a look at preg_last_error():

<?php preg_match('/[a-z]/', 'test'); var_dump(preg_last_error()); preg_match('invalid regex', 'test'); var_dump(preg_last_error()); ?> 

Where obviously first one is not an error, and second one is. But preg_last_error() returns int 0 both times.

Any ideas?

like image 666
Hosh Sadiq Avatar asked May 28 '12 00:05

Hosh Sadiq


People also ask

How do you check if a string is a regex in C#?

You can't detect regular expressions with a regular expression, as regular expressions themselves are not a regular language. However, the easiest you probably could do is trying to compile a regex from your textbox contents and when it succeeds you know that it's a regex. If it fails, you know it's not.

How do I check if a string matches in regex bash?

You can use the test construct, [[ ]] , along with the regular expression match operator, =~ , to check if a string matches a regex pattern (documentation). where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

How do you check if a string matches a regex in Java?

Variant 1: String matches() This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).


2 Answers

The simplest way to test if a string is a regex is:

if( preg_match("/^\/.+\/[a-z]*$/i",$regex)) 

This will tell you if a string has a good chance of being intended to be as a regex. However there are many string that would pass that check but fail being a regex. Unescaped slashes in the middle, unknown modifiers at the end, mismatched parentheses etc. could all cause problems.

The reason preg_last_error returned 0 is because the "invalid regex" is not:

  • PREG_INTERNAL_ERROR (an internal error)
  • PREG_BACKTRACK_LIMIT_ERROR (excessively forcing backtracking)
  • PREG_RECURSION_LIMIT_ERROR (excessively recursing)
  • PREG_BAD_UTF8_ERROR (badly formatted UTF-8)
  • PREG_BAD_UTF8_OFFSET_ERROR (offset to the middle of a UTF-8 character)
like image 91
Niet the Dark Absol Avatar answered Oct 12 '22 17:10

Niet the Dark Absol


Here is a good answer how to:

https://stackoverflow.com/a/12941133/2519073

if(@preg_match($yourPattern, null) === false){     //pattern is broken }else{     //pattern is real } 
like image 21
ya_dimon Avatar answered Oct 12 '22 19:10

ya_dimon