Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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 re替换为自定义函数_Python_Regex_Re - Fatal编程技术网

用Python re替换为自定义函数

用Python re替换为自定义函数,python,regex,re,Python,Regex,Re,一串 s = '{{a,b}} and {{c,d}} and {{0,2}}' 我想将每个{…}模式随机替换为内部列表中的一个项目,即: "a and d and 2" "b and d and 0" "b and c and 0" ... 我记得在模块re中有一种方法,不只是像re.sub那样简单地替换,而是有一个自定义替换功能,但我在文档中找不到了,可能我用了错误的关键字搜索 这不会给出任何输出: import re r = re.match('{{.*?}}', '{{a,

一串

s = '{{a,b}} and {{c,d}} and {{0,2}}'
我想将每个{…}模式随机替换为内部列表中的一个项目,即:

"a and d and 2"  
"b and d and 0"  
"b and c and 0"
...
我记得在模块re中有一种方法,不只是像re.sub那样简单地替换,而是有一个自定义替换功能,但我在文档中找不到了,可能我用了错误的关键字搜索

这不会给出任何输出:

import re

r = re.match('{{.*?}}', '{{a,b}} and {{c,d}} and {{0,2}}')
for m in r.groups():
    print(m)
你可以用

import random, re

def replace(match):
    lst = match.group(1).split(",")
    return random.choice(lst)

s = '{{a,b}} and {{c,d}} and {{0,2}}'

s = re.sub(r"{{([^{}]+)}}", replace, s)
print(s)
或者-如果你喜欢一行,那么不建议:

s = re.sub(
    r"{{([^{}]+)}}", 
    lambda x: random.choice(x.group(1).split(",")), 
    s)

您可以避免使用适当的正则表达式来提取模式:

import re, random

s = '{{a,b}} and {{c,d}} and {{0,2}}'
s = re.sub(r'{{(.*?),(.*?)}}', random.choice(['\\1', '\\2']), s)

# a and c and 0

文档中有一个使用repl函数的示例。还要注意,{}在正则表达式中有特殊的含义,如果需要文字匹配,则需要转义。@0x5453否,{{.*.}是有效的模式。没有必要逃避任何事情。它不是Android或C++ MSVC。你可以考虑‘R.SuBr’{{\W+,\W+}},lambda x:x.GrPrand。选择[1,2],s,但是它只支持两个值。您想生成一个结果还是所有可能的排列?谢谢您的回答。我希望自定义替换功能适用于任意长度的列表,这里只有2个项目,你知道吗?@Basj,拆分是任意长度列表的选项。但对于较小的长度,您可以在我的回答中看到使用该方法。