Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a given character is considered as 'special' by the Python regex engine?

Is there an easy way to verify that the given character has a special regex function?

Of course I can collect regex characters in a list like ['.', "[", "]", etc.] to check that, but I guess there is a more elegant way.

like image 255
Prag Avatar asked Mar 05 '15 17:03

Prag


People also ask

How do you check if a character is a special character in Python?

Then using the search() method we will search if any special character is present in the string or not. If no character is found the search() method will return None and then we can print that the string is accepted.

How do you check if a char is in a regex?

There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.

What regex engine does Python use?

Python has two major implementations, the built in re and the regex library. Ruby 1.8, Ruby 1.9, and Ruby 2.0 and later versions use different engines; Ruby 1.9 integrates Oniguruma, Ruby 2.0 and later integrate Onigmo, a fork from Oniguruma. The primary regex crate does not allow look-around expressions.


1 Answers

You could use re.escape. For example:

>>> re.escape("a") == "a"
True
>>> re.escape("[") == "["
False

The idea is that if a character is a special one, then re.escape returns the character with a backslash in front of it. Otherwise, it returns the character itself.

like image 71
JuniorCompressor Avatar answered Sep 17 '22 23:09

JuniorCompressor