Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.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正则表达式将组1替换为特定字符串_Python_Regex - Fatal编程技术网

Python正则表达式将组1替换为特定字符串

Python正则表达式将组1替换为特定字符串,python,regex,Python,Regex,我想知道如何用python中的正则表达式替换具有特定字符串的组1 问题1: str = "aaa bbb ccc" regex = "\baaa (bbb)\b" repl = "111 bbb 222" s1 = "bBb" regex = "(?<=\baaa )" + s1 + "\b" # may not suitable repl = "XxX " + s1 + " YyY" s1 = "bbb" regex = "(?<=\baaa )" + s1 + "\b"

我想知道如何用python中的正则表达式替换具有特定字符串的组1

问题1:

str = "aaa bbb ccc"
regex = "\baaa (bbb)\b"
repl = "111 bbb 222"
s1 = "bBb"
regex = "(?<=\baaa )" + s1 + "\b"  # may not suitable
repl = "XxX " + s1 + " YyY"
s1 = "bbb"
regex = "(?<=\baaa )" + s1 + "\b"  # may not suitable
repl = "XxX " + s1 + " YyY"
使用正则表达式匹配str,匹配“aaa bbb”,并将group1“bbb”替换为“111 bbb 222”,得到结果“aaa 111 bbb 222 ccc”

感谢@RomanPerekhrest和@janos的lookback方法

我想知道如何解决更一般的情况:

问题2:

str = "aaa bbb ccc"
regex = "\baaa (bbb)\b"
repl = "111 bbb 222"
s1 = "bBb"
regex = "(?<=\baaa )" + s1 + "\b"  # may not suitable
repl = "XxX " + s1 + " YyY"
s1 = "bbb"
regex = "(?<=\baaa )" + s1 + "\b"  # may not suitable
repl = "XxX " + s1 + " YyY"
在原始字符串中进行匹配时,忽略子字符串(s1除外)的大小写

问题3:

str = "aaa bbb ccc"
regex = "\baaa (bbb)\b"
repl = "111 bbb 222"
s1 = "bBb"
regex = "(?<=\baaa )" + s1 + "\b"  # may not suitable
repl = "XxX " + s1 + " YyY"
s1 = "bbb"
regex = "(?<=\baaa )" + s1 + "\b"  # may not suitable
repl = "XxX " + s1 + " YyY"
在原始字符串中进行匹配和替换时,忽略除s1以外的子字符串的大小写

问题4:

str = "aaa bbb ccc"
regex = "\baaa (bbb)\b"
repl = "111 bbb 222"
s1 = "bBb"
regex = "(?<=\baaa )" + s1 + "\b"  # may not suitable
repl = "XxX " + s1 + " YyY"
s1 = "bbb"
regex = "(?<=\baaa )" + s1 + "\b"  # may not suitable
repl = "XxX " + s1 + " YyY"

如果有办法用python上的正则表达式替换原始字符串上的第1组?

您可以使用
re
包和正向查找:

import re
s = "aaa bbb ccc"
regex = r"\b(?<=aaa )(bbb)\b"
repl = "111 bbb 222"
print(re.sub(regex, repl, s))
注意我在那里做的更改:


  • 正则表达式中的
    aaa
    前缀被包装在
    (?首先,不要使用
    str
    作为变量名。它是Python中的保留关键字

    import re
    
    str1 = "aaa bbb ccc"
    re.sub("bbb", "111 bbb 222", str1)
    Out[11]: 'aaa 111 bbb 222 ccc'
    

    要替换顺序
    bbb
    ,其前面应加上顺序
    aaa
    ,请使用以下方法:

    s = "aaa bbb ccc"
    regex = r"(?<=aaa )bbb\b"
    repl = "111 bbb 222"
    
    str_replaced = re.sub(regex, repl, s)
    print(str_replaced)
    


    (?我只想将“bbb”开头与“aaa”匹配,所以这个答案可能不合适。谢谢!那么我可以用python的正则表达式替换group1,或者我可以这样使用吗?在您的简单示例中,您甚至不需要将
    bbb
    包含到捕获组中,只需使用如上所示的lookback和单词边界。我将把sequence
    bbb
    作为前面带有
    的单独单词进行匹配>“aaa”
    您的一般场景听起来既简单又复杂。您能详细说明一下吗?很抱歉刚才删除了一些描述。请再次检查问题的详细信息。检查。@Wiktor,谢谢您的演示,我在上面添加了问题2-4。