在 Python 中反转正则表达式 [英] Reversing a regular expression in Python

查看:49
本文介绍了在 Python 中反转正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想反转一个正则表达式.IE.给定一个正则表达式,我想生成与该正则表达式匹配的 any 字符串.

我知道如何使用有限状态机从理论计算机科学背景中做到这一点,但我只想知道是否有人已经编写了一个库来做到这一点.:)

我使用的是 Python,所以我想要一个 Python 库.

重申一下,我只想要 一个 匹配正则表达式的字符串.像 "."或.*"将使无限数量的字符串与正则表达式匹配,但我不关心所有选项.

我愿意让这个库只处理正则表达式的某个子集.

解决方案

其他人有类似(重复?)的问题 here,我想为 使用 Python 生成随机字符串,我一直在研究.

它包含一个方法,xeger(),它允许您从正则表达式创建一个字符串:

<预><代码>>>>导入 rstr>>>rstr.xeger(r'[A-Z]\d[A-Z]\d[A-Z]\d')u'M5R 2W4'

现在,它适用于大多数基本的正则表达式,但我相信它可以改进.

I want to reverse a regular expression. I.e. given a regular expression, I want to produce any string that will match that regex.

I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)

I'm using Python, so I'd like a Python library.

To reiterate, I only want one string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.

I'm willing for this library to only work on a certain subset of regex.

解决方案

Somebody else had a similar (duplicate?) question here, and I'd like to offer a little helper library for generating random strings with Python that I've been working on.

It includes a method, xeger() that allows you to create a string from a regex:

>>> import rstr
>>> rstr.xeger(r'[A-Z]\d[A-Z] \d[A-Z]\d')
u'M5R 2W4'

Right now, it works with most basic regular expressions, but I'm sure it could be improved.

这篇关于在 Python 中反转正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆