Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python re match strings not ending with word

Tags:

python

regex

I'm trying to match all strings not ending with a specific word. For some reason the following doesn't work:

>> import re
>> my_str = 'static/assets/img/favicon.ico'
>> re.search('^static.+(?!ico)$', my_str)
<_sre.SRE_Match at 0x7f08b9773440>

Can you please explain why it's not working and how to fix it?

like image 552
David Tzoor Avatar asked Jan 28 '26 14:01

David Tzoor


2 Answers

I think you want to use a negative lookbehind, not lookahead.

^static.+$(?<!ico)

See demo at regex101 if this is what you needed.


(?!ico)$ or $(?!ico) would look if there is not ico after the end which is impossible.

like image 136
bobble bubble Avatar answered Jan 31 '26 02:01

bobble bubble


You should use:

print re.search(r'^(?!.*ico$)static.+', my_str)
None

(?!.*ico$) asserts that string doesn't end with ico

like image 43
anubhava Avatar answered Jan 31 '26 03:01

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!