Python基于正则表达式格式生成字符串

时间:2015-07-02 04:07:02

标签: python regex

我在python中学习regex时遇到了一些困难。我想将我的龙卷风Web路由配置和参数解析为请求路径字符串,而不需要处理程序request.path方法。 例如,我的路线模式如下:

/entities/([0-9]+)

/product/([0-9]+/actions

预期结果与整数参数(123)组合将是一个字符串,如:

/entities/123

/product/123/actions

如何根据该模式生成字符串?

非常感谢你!

1 个答案:

答案 0 :(得分:1)

这可能与以下内容重复:
Reversing a regular expression in Python
Generate a String that matches a RegEx in Python

使用@bjmc提供的答案,解决方案的工作原理如下:

>>> import rstr
>>> intermediate = rstr.xeger(\d+)
>>> path = '/product/' + intermediate + '/actions'

根据您希望中间整数的长度,您可以替换正则表达式:\d{1,3}

相关问题