简体   繁体   中英

Python Regex to search for NOT and AND expression

Lots of great regex answers here but I haven't been able to find anything that works for me. Here is the situation:

I have a large list of numbers. Let's say it is just a list of numbers from 1 to 100 and I only want to use the list that contains 10, 20, and 50. But the way the code is built (and can't be changed!) is to ignore by the regex expression not accept. So, I can't just say ^10$|^20$|^50$ instead I need to NOT them and then AND them.

I have tried this:

(?!^10$)(?!^20$)(?!^50$) 

with no luck and can't seem to find anything anywhere that is working.

Any thoughts? Many Thanks!

ps I just made this particular example up to show what I am doing, I wouldn't be using regex is this was the actual problem I had....:-)

If I understand your problem correctly, what you need is something like this:

(?!^10$)(?!^20$)(?!^50$)^.*$

This matches when the line has something that is different from "10" , "20" or "50" .

However, it seems that this is a rather cumbersome way of dealing with your problem. Wouldn't something more on this lines be better?

import re
pattern = re.compile(r"^(?:10|20|50)$")
for text in list_of_texts:
  m = pattern.match(text)
  if m is not None:
    print "Found something interesting (not 10, nor 20 nor 50): %s" % text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM