Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有条件正则表达式替换_Python_Regex - Fatal编程技术网

Python 有条件正则表达式替换

Python 有条件正则表达式替换,python,regex,Python,Regex,使用Python,您可以在替换文本之前检查组是否为空 例如: [user] John Marshal --> [user]<br><strong>Jonh Marshal<strong> John Marshal --> <strong>Jonh Marshal<strong> [user]约翰·马歇尔-->[user]约翰·马歇尔 约翰·马歇尔-->约翰·马歇尔 正则表达式应该使用is,但只有在找到组

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

例如:

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

John Marshal   -->   <strong>Jonh Marshal<strong>
[user]约翰·马歇尔-->[user]
约翰·马歇尔 约翰·马歇尔-->约翰·马歇尔
正则表达式应该使用is,但只有在找到组1时才使用“条件”插入

title = re.sub(r'^\s*(\[.*?\])?\s*(.*)', r'\1<br><strong>\2</strong>', title)
title=re.sub(r'^\s*(\[.*?\])?\s*(.*),r'\1
\2',title)
始终找到第一组,因为您允许空匹配

您希望至少匹配一个字符,而不是0或更多字符,因此请使用
+?

title = re.sub(r'^\s*(\[.+?\])?\s*(.*)', r'\1<br><strong>\2</strong>', title)
title=re.sub(r'^\s*(\[.+?\])?\s*(.*),r'\1
\2',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)
试试看:
title=re.sub(r'^\s*(\[.+?\])?\s*(.*),r'\1
\2',title) 除重复错误外: title=re.sub(r'^\s*(.*),r'\1',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)
def title_sub(匹配):
如果匹配。组(1):
返回“{}
{}”.format(*match.groups()) 返回'{}'.format(match.group(2)) title=re.sub(r'^\s*(\[.+?\])?\s*(.*),title\u sub,title)
演示:

>>re.sub(r'^\s*(\[.+?\])?\s*(.*),标题为“[user]John Marshal')
“[用户]
约翰·马歇尔” >>>re.sub(r'^\s*(\[.+?\])?\s*(.*),标题为“约翰·马歇尔”) “约翰·马歇尔”
要在Python中使用正则表达式进行条件替换,我提出了以下解决方案:

@classmethod
def normalize_query_string(cls, query_string):

    def replace_fields(match):
        x = match.group("field")
        if x == "$certHash":
            return "ci.C.H:"
        return "{}:".format(x)

    result = re.sub(r"(?P<field>\$[\w.]+):", replace_fields, query_string)
    return result
@classmethod
def规范化查询字符串(cls,查询字符串):
def replace_字段(匹配):
x=匹配组(“字段”)
如果x==“$certHash”:
返回“ci.C.H:”
返回“{}:”.format(x)
result=re.sub(r“(?P\$[\w.]+):”,替换\u字段,查询\u字符串)
返回结果

谢谢!我用尝试,解决我的问题。我想知道纯正则表达式是否可能。你不能做条件替换,不。如果我使用函数,我不能在替换正则表达式中使用组名,可以吗?@Lerner:当然可以。传入的match对象允许您访问所有组,包括命名组。@勒纳:您可以使用
'{variable4group}'.format(**match.groupdict())
@classmethod
def normalize_query_string(cls, query_string):

    def replace_fields(match):
        x = match.group("field")
        if x == "$certHash":
            return "ci.C.H:"
        return "{}:".format(x)

    result = re.sub(r"(?P<field>\$[\w.]+):", replace_fields, query_string)
    return result