Skip to content Skip to sidebar Skip to footer

Regexp Look For Part But Exclude If

Right so RegExp is fairly new to me and its still puzzling me. Anyway I managed to look for almost all the names I want to but now I have to look for names that have specific part

Solution 1:

Use negative look-ahead:

^(?!.*dog).*cat.*$

It will first test that there is no dog further in the string. If negative look-ahead succeeds, then it goes on to match the string containing cat. You might want to enable ignore case in it using (?i) flag.

In python, you can also use re.IGNORECASE:

>>>import re>>>ignorecase = re.compile(r'(?i)(?!.*dog).*cat.*')>>>print ignorecase.match("CatBlablablaDog")
None
>>>>>>print ignorecase.match("blablaCatBlabla")
<_sre.SRE_Match object at 0x956b090>
>>>>>>print ignorecase.match("Dog_blabla_Cat")
None

Solution 2:

Providing an alternative, non-regex solution to @Rohit Jain's answer

Single line without regular expressions (playing with it in the ):

>>> (lambda s: 'cat'in s and'dog'notin s)("CatBlablablaDog".lower())
False>>> (lambda s: 'cat'in s and'dog'notin s)("blablaCatBlabla".lower())
True>>> (lambda s: 'cat'in s and'dog'notin s)("Dog_blabla_Cat".lower())
False

Using a more formal function of some sorts:

deffindExclude(string, search_str, exclude_str):
    string = string.lower()
    return search_str in string and exclude_str notin string

print findExclude("CatBlablablaDog", 'cat', 'dog')
print findExclude("blablaCatBlabla", 'cat', 'dog')
print findExclude("Dog_blabla_Cat", 'cat', 'dog')

Post a Comment for "Regexp Look For Part But Exclude If"