Regular expressions to exclude a specific format from a list of strings

Question:

I started recently working with regular expressions and they are not very clear to me at the moment.

I have a list of strings:

l = ['1P', '2.2', '1.2MP', '1.2P', '1.2.3', '1.2.3 P', '4.5.6']

How can i exclude all the strings that contains this format : x.y.z?

So the list will look like this :

l = ['1P', '2.2', '1.2MP', '1.2P']
Asked By: rzss275

||

Answers:

import re
pattern = "d+.d+.d+"  # 3 digits separated by two dots, each one with 1 or more digit
l = ['1P', '2.2', '1.2MP', '1.2P', '1.2.3', '1.2.3 P', '4.5.6']
matched = [item for item in l if not re.search(pattern, item)]
# matched = ['1P', '2.2', '1.2MP', '1.2P']

You can see re.serach() and how it matches the pattern.

Answered By: Jonathan Ciapetti

Below is my regex.

^(?!(?:.+?[.]){2}).*$

^(?!(?:.+?[.]{2}) -> This is a negative lookahead. This part ensures that string are not in x.y.z format.

.* -> If the above is true then match entire string.

Demo link.

Answered By: novice
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.