Home > Blockchain >  Regex Negating a character group while matching another group at the same time
Regex Negating a character group while matching another group at the same time

Time:01-09

I am trying to create a regex wherein IF a certain char set is found, it should not return any match but if that char set is not found then it should return the match found by the rest of the regexp. So far example:

re.search('^(?:(?!>).) $','>Jack Sparrow/Harry>Potter')
>>>  No match found as > present which is what I wanted
re.search('(^(?:(?!>).) $)(/Harry)','Jack Sparrow/Harry Potter')
>>>  No match found but I was expecting it to return true as > is not there while '/Harry' is

What am I doing wrong?

CodePudding user response:

If you want to make sure the string does not contain < and contains /Harry you need to match the whole string making sure it has no < char.

So you can use

re.fullmatch(r'[^>]*?/Harry[^>]*', text)
re.search(r'^[^>]*?/Harry[^>]*$', text)
re.match(r'[^>]*?/Harry[^>]*$', text)

Details:

  • ^ - start of string
  • [^>]*? - any zero or more chars other than > as few as possible
  • /Harry - a fixed string
  • [^>]* - zero or more chars other than > as many as possible
  • $ - end of string.
  •  Tags:  
  • Related