Home > database >  Python regex negation
Python regex negation

Time:10-09

Below are few example strings

as-jfk-interface-module-trojan-7.100.110-12350009

network-refresh-core-3.3.909-99950009

network-challenge7-7-ui-module-8.23.590-12350009

and I use the following regex to get the version part of the string like 7.100.110-12350009

regex:

(0|(?:[1-9]\d*))(?:\.(0|(?:[1-9]\d*))(?:\.(0|(?:[1-9]\d*)))?(?:\-([\w][\w\.\-_]*))?)?

While trying to match the word portion like as-jfk-interface-module-trojan or network-challenge7-7-ui-module by negation, [^(0|(?:[1-9]\d*))(?:\.(0|(?:[1-9]\d*))(?:\.(0|(?:[1-9]\d*)))?(?:\-([\w][\w\.\-_]*))?)?], it says Invalid regular expression: unbalanced parenthesis

st = "as-jfk-interface-module-trojan-7.100.110-12350009"
pattern = "(0|(?:[1-9]\d*))(?:\.(0|(?:[1-9]\d*))(?:\.(0|(?:[1-9]\d*)))?(?:\-([\w][\w\.\-_]*))?)?"
re.search(pattern, st)

What am I doing incorrect ?

CodePudding user response:

A negated character class doesn't work like that!

[^abc] is exactly the same as [^cba], it means match a character that is not a or b or c. It doesn't mean: don't match abc.

To get the word portion you could use for example

r"[a-z\d-] (?=-\d\.)"

CodePudding user response:

If you are using VScode, install "reg exp explain" addon. It will show you in graphical way,your reg exp and can see what is wrong.

  • Related