Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use special characters inside a regex set?

Tags:

python

regex

I'm using python, and right now I would like something to match up until a space or the end of the string, so I had the regex ".*?[ $]".

But after testing that and seeing it didn't work I looked at the documentation and found that special characters lose their special meaning inside sets.

Is there a way to put this meaning back into the set?

like image 989
Pro Q Avatar asked Jul 11 '15 15:07

Pro Q


2 Answers

That's because you regex is incorrect,your regex will match .*?+space or character $ literally.(Note that every regex character except ] within character class will be escaped)

Instead you can use a positive look ahead :

.*(?= |$)

See demo https://regex101.com/r/sF3qU1/1

like image 73
Mazdak Avatar answered Oct 26 '22 16:10

Mazdak


I think that for your purpose a word anchor would be sufficient. From re internal documentation (run pydoc re if you use an Unix-like system):

\b       Matches the empty string, but only at the start or end of a word.

So, your regex would look like:

".*?\\b"

or

r".*?\b"
like image 29
werkritter Avatar answered Oct 26 '22 17:10

werkritter