python - Python3 re negative lookahead like this -


i want find string closet @@ below

def get_closet(ss):     m = re.search('(?<=@@)(.*)$', ss, re.i)     if m:         print('find')         print(m.groups())     else:         print('not find')    str1 = '@@ af @@ bv @@ cx @@ ddfff'  # should return `ddfff` str2 = ' ddfff'  # should return `ddfff`  x in str1, str2:     get_closet(x) 

i find m = re.search('((?!@@).)*$', ss, re.i|re.s) when input str1,it return @ ddfff not ddfff

you can use (?:@@| )?([^@@ ]+)$:

import re  print(re.findall('(?:@@| )?([^@@ ]+)$', '@@ af @@ bv @@ cx @@ ddfff')) # ['ddfff'] print(re.findall('(?:@@| )?([^@@ ]+)$', ' ddfff')) # ['ddfff'] 

but, don't need regex:

def foo(string):     try:         return string[string.rindex('@@'):].strip('@@ ')     except valueerror:  # if no @@         return string.strip()  string = '@@ af @@ bv @@ cx @@ ddfff' print(foo(string)) # 'ddfff' string = ' ddfff' print(foo(string)) # 'ddfff' 

or more generic:

def foo(sep, string):     try:         return string[string.rindex(sep):].strip(sep + ' ')     except valueerror:  # if no sep         return string.strip() 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -