有条件的正则表达式替换

2024-06-28

使用Python,您可以在替换文本之前检查组是否为空?

Example:

[user] John Marshal   -->   [user]<br><strong>Jonh Marshal<strong>

John Marshal   -->   <strong>Jonh Marshal<strong>

正则表达式应该使用此 is,但只有在找到组 1 时才使用“条件”插入 。

title = re.sub(r'^\s*(\[.*?\])?\s*(.*)', r'\1<br><strong>\2</strong>', title)

第一组是always发现是因为您允许空匹配。

您想要匹配至少一个字符,而不是 0 个或多个字符,因此使用.+?:

title = re.sub(r'^\s*(\[.+?\])?\s*(.*)', r'\1<br><strong>\2</strong>', title)

现在,如果第一组缺失,比赛将引发异常。利用它:

try:
    title = re.sub(r'^\s*(\[.+?\])?\s*(.*)', r'\1<br><strong>\2</strong>', title)
except re.error:
    title = re.sub(r'^\s*(.*)', r'<strong>\1</strong>', title)

另一种方法是使用函数来进行替换:

def title_sub(match):
    if match.group(1):
        return '{}<br><strong>{}</strong>'.format(*match.groups())
    return '<strong>{}</strong>'.format(match.group(2))

title = re.sub(r'^\s*(\[.+?\])?\s*(.*)', title_sub, title)

Demo:

>>> re.sub(r'^\s*(\[.+?\])?\s*(.*)', title_sub, '[user] John Marshal')
'[user]<br><strong>John Marshal</strong>'
>>> re.sub(r'^\s*(\[.+?\])?\s*(.*)', title_sub, 'John Marshal')
'<strong>John Marshal</strong>'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有条件的正则表达式替换 的相关文章

随机推荐