Python 3.x python3根据给定的正则表达式生成x值
我正在尝试使用Python 3.x python3根据给定的正则表达式生成x值,python-3.x,regex,Python 3.x,Regex,我正在尝试使用rstr基于正则表达式定义生成值 以下是有效的方法: [root@localhost ~]# python3 Python 3.6.8 (default, Nov 16 2020, 16:55:22) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for
rstr
基于正则表达式定义生成值
以下是有效的方法:
[root@localhost ~]# python3
Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>import rstr
>>>print(rstr.xeger(r'[2-9]\d{11}'))
>>>867050869842
现在,我想编写一个脚本,将任何正则表达式作为参数,并生成10次输出:
#!/usr/bin/python3
import sys
import rstr
if len(sys.argv) != 2:
print("[+] Usage ./regexgen.py regex")
exit()
regex = sys.argv[1]
for string in range(10):
print(rstr.xeger(r'{1}')).format(regex)
但执行脚本时失败,出现以下错误:
[root@localhost ~]# python3 script2.py [2-9]\d{11}
Traceback (most recent call last):
File "script2.py", line 18, in <module>
print(rstr.xeger(r'{1}')).format(regex)
File "/usr/local/lib/python3.6/site-packages/rstr/xeger.py", line 63, in xeger
parsed = re.sre_parse.parse(pattern)
File "/usr/lib64/python3.6/sre_parse.py", line 855, in parse
p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
File "/usr/lib64/python3.6/sre_parse.py", line 416, in _parse_sub
not nested and not items))
File "/usr/lib64/python3.6/sre_parse.py", line 616, in _parse
source.tell() - here + len(this))
sre_constants.error: nothing to repeat at position 0
[root@localhost~]#python3 script2.py[2-9]\d{11}
回溯(最近一次呼叫最后一次):
文件“script2.py”,第18行,在
打印(rstr.xeger(r'{1}')).format(regex)
文件“/usr/local/lib/python3.6/site packages/rstr/xeger.py”,第63行,在xeger中
parsed=re.sre_parse.parse(模式)
文件“/usr/lib64/python3.6/sre_parse.py”,第855行,在parse中
p=\u parse\u sub(源、模式、标志和SRE\u标志\u VERBOSE,0)
文件“/usr/lib64/python3.6/sre_parse.py”,第416行,在_parse_sub中
非嵌套和非项目)
文件“/usr/lib64/python3.6/sre_parse.py”,第616行,in_parse
source.tell()-here+len(this))
sre_constants.error:在位置0处没有要重复的内容
我的猜测是,xeger
无法使用format函数解析插入的正则表达式。尝试以下方法:
import sys
import rstr
if len(sys.argv) != 2:
print("[+] Usage ./regexgen.py regex")
exit()
regex = sys.argv[1] # regex passed as arg [2-9]\d{11}
for string in range(10):
print(rstr.xeger(regex))
输出:
302799318288
303010436356
523231185691
537677558398
824580634154
398638175299
546948835775
845745020055
456616189703
579459609359
试试这个:
import sys
import rstr
if len(sys.argv) != 2:
print("[+] Usage ./regexgen.py regex")
exit()
regex = sys.argv[1] # regex passed as arg [2-9]\d{11}
for string in range(10):
print(rstr.xeger(regex))
输出:
302799318288
303010436356
523231185691
537677558398
824580634154
398638175299
546948835775
845745020055
456616189703
579459609359
非常感谢。工作起来像个符咒:)!非常感谢。工作起来像个符咒:)!