Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.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
Python3正则表达式逃逸函数_Python_Regex_Python 3.x - Fatal编程技术网

Python3正则表达式逃逸函数

Python3正则表达式逃逸函数,python,regex,python-3.x,Python,Regex,Python 3.x,因此,我得到了一个可变长度的数字串,我需要使用该字符串中的数字找到所有可能的数字组合,其中只有中间的数字可以更改,例如: 如果给我123,我需要找到1x2xy3的组合,其中x,y是任何数字 如果给我5312,我需要找到5a3b1c2的组合,其中a、b、c是任意数字 我认为使用python的re.escape函数可以实现这一点,这就是我所了解的: #Given the digits '123' from STDIN #create a string "1\d2\d3" my_regex_stri

因此,我得到了一个可变长度的数字串,我需要使用该字符串中的数字找到所有可能的数字组合,其中只有中间的数字可以更改,例如:

如果给我123,我需要找到1x2xy3的组合,其中x,y是任何数字

如果给我5312,我需要找到5a3b1c2的组合,其中a、b、c是任意数字

我认为使用python的
re.escape
函数可以实现这一点,这就是我所了解的:

#Given the digits '123' from STDIN

#create a string "1\d2\d3"
my_regex_string = '\d'.join(input().split())

#Set x as starting point, set y as limit (not the most efficient)
x = 10**(len(my_regex_string)-1) * int(my_regex_string[0])
y = 10**(len(my_regex_string)-1) * (int(my_regex_string[0]) + 1)

while x < y:
    if bool(re.match(re.escape(p), str(x)))
        print(x)
    x+=1
#给定STDIN中的数字“123”
#创建字符串“1\d2\d3”
my_regex_string='\d'.join(输入().split())
#将x设置为起点,将y设置为限制(不是最有效的)
x=10**(len(my_regex_string)-1)*int(my_regex_string[0])
y=10**(len(my_regex_string)-1)*(int(my_regex_string[0])+1)
当x

我需要反馈,我的方法有意义吗?这项任务可以用regex完成吗?还是我需要另一种方法?

我认为,就像wolfrevokcats所说的那样,pythonic的方法是使用itertools.product函数。类似于以下代码:

from itertools import product

s = input()
r = "{}".join(list(s))
c = [int(r.format(*f)) for f in product(range(0,10), repeat=len(s)-1)]

这里有一个使用itertools的解决方案,可能不是最复杂的,但它可以工作:

>>> import itertools
>>> x = map(lambda z: [s[i] + str(z[i]) for i in range(len(s)-1)] + [s[-1]], list(itertools.product(range(10), repeat=len(s)-1)))
>>> y = map(lambda z: "".join(z), x)
>>> list(y)

为什么不使用
itertools
?为什么要使用regex?使用regex进行此操作是一个非常糟糕的选择。使用
itertools.product
。您是要查找总数,还是要获取所有解决方案的列表?您是想创建一个可以匹配这些组合的正则表达式,还是只创建这些组合?正则表达式应该是
1\d2\d3
,等等。要生成,它只是简单的嵌套循环,您不需要任何特殊的处理。真正干净的解决方案!干得好