Home > Mobile >  Regular expressions to exclude a specific format from a list of strings
Regular expressions to exclude a specific format from a list of strings

Time:07-10

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']

CodePudding user response:

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']

Here the re.search() docs, and how it matches the pattern.

CodePudding user response:

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.

  • Related