正则表达式 - Python re.sub() 的一个奇怪问题?
大家讲道理
大家讲道理 2017-04-18 09:59:51
0
4
512
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
左手右手慢动作

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)
黄舟

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
左手右手慢动作
import re
data = re.sub(r'@(\w+)', '\\1','@yangxg @zengshao @zmrenwu')
print data
刘奇
result = re.sub(r'@(\w+)', lambda mo: mo.group(1), '@yangxg @zengshao @zmrenwu')
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!