Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression - Match pattern that does not contain a string

Tags:

python

regex

I'm quite new to regular expression, and have been searching around for away to do this without success. Given a string, I want to remove any pattern that starts with "abc", ends with "abc", and does not contain "abc" in the middle. If I do

'abc.*(abc).*abc'

it will match any patter starts with "abc", ends with "abc", and does contain "abc" in the middle. How do I do the opposite. I try

'abc.*^(abc).*abc'

but it won't work.

like image 620
user108372 Avatar asked May 25 '26 13:05

user108372


2 Answers

Your syntax for trying to negate part of your pattern is incorrect.

Also, ^ outside of a character class asserts position at the beginning of the string. You need to use a Negative Lookahead assertion and be sure to anchor the entire pattern.

^abc(?:(?!abc).)*abc$

Live Demo

like image 97
hwnd Avatar answered May 28 '26 03:05

hwnd


You can try the following pattern :

^abc((?!abc).)*abc$

(?!abc) is Negative Lookahead - Assert that it is impossible to match the abc inside your string.

Regular expression visualization

Debuggex Demo

like image 35
Mazdak Avatar answered May 28 '26 03:05

Mazdak



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!