Mario7 Mario7 - 3 years ago 89
Python Question

Python3 re negative lookahead like this

I want to find a string which closet to

@@
like 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`
for x in str1, str2:
get_closet(x)





I find
m = re.search('((?!@@).)*$', ss, re.I|re.S)
but when input is
str1
,it will return
@ DDFFF
not
DDFFF

Answer Source

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

import re

print(re.findall('(?:@@| )?([^@@ ]+)$', '@@ AF @@ BV @@ CX @@ DDFFF'))
# ['DDFFF']
print(re.findall('(?:@@| )?([^@@ ]+)$', ' DDFFF'))
# ['DDFFF']

But, you don't necessarily need a 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 even the more generic:

def foo(sep, string):
    try:
        return string[string.rindex(sep):].strip(sep + ' ')
    except ValueError:  # if no sep
        return string.strip()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download