ringa_lee2017-04-18 10:01:51
When
matches the second bracket, the value is mo.group(2)
mo.group(1)
没匹配到就 None
Got it
def mark(mo):
# print(mo.group(1))
for i in range(1, 4):
match_result = mo.group(i)
if match_result is not None:
print(i)
return match_result
re_sub = re.sub(r'@(yangxg)|@(zengshao)|@(zmrenwu)', mark, '@yangxg @zengshao @zmrenwu')
print(re_sub)
黄舟2017-04-18 10:01:51
Maybe it’s better to write like this? The output meets your requirements
def mark(mo):
print(mo.group(1))
return mo.group(1)[1:]
data = re.sub(r'(@\w+)', mark, '@yangxg @zengshao @zmrenwu')
print data
ringa_lee2017-04-18 10:01:51
import re
data = re.sub(r'@(\w+)', '\\1','@yangxg @zengshao @zmrenwu')
print data
怪我咯2017-04-18 10:01:51
result = re.sub(r'@(\w+)', lambda mo: mo.group(1), '@yangxg @zengshao @zmrenwu')