exrex.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #!/usr/bin/env python
  2. # This file is part of exrex.
  3. #
  4. # exrex is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # exrex is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with exrex. If not, see < http://www.gnu.org/licenses/ >.
  16. #
  17. # (C) 2012- by Adam Tauber, <[email protected]>
  18. try:
  19. from future_builtins import map, range
  20. except:
  21. pass
  22. from re import sre_parse
  23. from itertools import product, chain, tee
  24. from random import choice,randint
  25. import string
  26. __all__ = ('generate', 'CATEGORIES', 'count', 'parse', 'getone')
  27. CATEGORIES = {'category_space' : sorted(sre_parse.WHITESPACE)
  28. ,'category_digit' : sorted(sre_parse.DIGITS)
  29. ,'category_any' : [chr(x) for x in range(32, 123)]
  30. ,'category_word' : sorted( frozenset(string.ascii_letters + string.digits + "_") )
  31. }
  32. def comb(g, i):
  33. for c in g:
  34. g2,i = tee(i)
  35. for c2 in g2:
  36. yield c+c2
  37. def mappend(g, c):
  38. for cc in g:
  39. yield cc+c
  40. def _in(d):
  41. ret = []
  42. neg = False
  43. for i in d:
  44. if i[0] == 'range':
  45. subs = map(chr, range(i[1][0], i[1][1]+1))
  46. if neg:
  47. for char in subs:
  48. try:
  49. ret.remove(char)
  50. except:
  51. pass
  52. else:
  53. ret.extend(subs)
  54. elif i[0] == 'literal':
  55. if neg:
  56. try:
  57. ret.remove(chr(i[1]))
  58. except:
  59. pass
  60. else:
  61. ret.append(chr(i[1]))
  62. elif i[0] == 'category':
  63. subs = CATEGORIES.get(i[1], [''])
  64. if neg:
  65. for char in subs:
  66. try:
  67. ret.remove(char)
  68. except:
  69. pass
  70. else:
  71. ret.extend(subs)
  72. elif i[0] == 'negate':
  73. ret = list(CATEGORIES['category_any'])
  74. neg = True
  75. return ret
  76. def prods(orig, ran, items):
  77. for o in orig:
  78. for r in ran:
  79. for s in product(items, repeat=r):
  80. yield o+''.join(s)
  81. def ggen(g1, f, *args, **kwargs):
  82. for a in g1:
  83. g2 = f(*args, **kwargs)
  84. if isinstance(g2, int):
  85. yield g2
  86. else:
  87. for b in g2:
  88. yield a+b
  89. def _gen(d, limit=20, count=False):
  90. """docstring for _gen"""
  91. ret = ['']
  92. strings = 0
  93. for i in d:
  94. if i[0] == 'in':
  95. subs = _in(i[1])
  96. if count:
  97. strings = (strings or 1) * len(subs)
  98. ret = comb(ret, subs)
  99. elif i[0] == 'literal':
  100. ret = mappend(ret, chr(i[1]))
  101. elif i[0] == 'category':
  102. subs = CATEGORIES.get(i[1], [''])
  103. if count:
  104. strings = (strings or 1) * len(subs)
  105. ret = comb(ret, subs)
  106. elif i[0] == 'any':
  107. subs = CATEGORIES['category_any']
  108. if count:
  109. strings = (strings or 1) * len(subs)
  110. ret = comb(ret, subs)
  111. elif i[0] == 'max_repeat':
  112. chars = filter(None, _gen(list(i[1][2]), limit))
  113. if i[1][1]+1 - i[1][0] >= limit:
  114. ran = range(i[1][0], i[1][0]+limit)
  115. else:
  116. ran = range(i[1][0], i[1][1]+1)
  117. if count:
  118. for i in ran:
  119. strings += pow(len(chars), i)
  120. ret = prods(ret, ran, chars)
  121. elif i[0] == 'branch':
  122. subs = list(chain.from_iterable(_gen(list(x), limit) for x in i[1][1]))
  123. if count:
  124. strings = (strings or 1) * (len(subs) or 1)
  125. ret = comb(ret, subs)
  126. elif i[0] == 'subpattern':
  127. if count:
  128. strings = (strings or 1) * (sum(ggen([0], _gen, i[1][1], limit=limit, count=True)) or 1)
  129. ret = ggen(ret, _gen, i[1][1], limit=limit, count=False)
  130. # ignore ^ and $
  131. elif i[0] == 'at':
  132. continue
  133. elif i[0] == 'not_literal':
  134. subs = list(CATEGORIES['category_any'])
  135. subs.remove(chr(i[1]))
  136. if count:
  137. strings = (strings or 1) * len(subs)
  138. ret = comb(ret, subs)
  139. elif i[0] == 'assert':
  140. print i[1][1]
  141. continue
  142. else:
  143. #print('[!] cannot handle expression ' + repr(i))
  144. raise Exception('[!] cannot handle expression ' + repr(i))
  145. if count:
  146. return strings
  147. return ret
  148. def _randone(d, limit=20):
  149. """docstring for _randone"""
  150. ret = ''
  151. for i in d:
  152. if i[0] == 'in':
  153. ret += choice(_in(i[1]))
  154. elif i[0] == 'literal':
  155. ret += chr(i[1])
  156. elif i[0] == 'category':
  157. ret += choice(CATEGORIES.get(i[1], ['']))
  158. elif i[0] == 'any':
  159. ret += choice(CATEGORIES['category_any'])
  160. elif i[0] == 'max_repeat':
  161. chars = filter(None, _gen(list(i[1][2]), limit))
  162. if i[1][1]+1 - i[1][0] >= limit:
  163. min,max = i[1][0], i[1][0]+limit
  164. else:
  165. min,max = i[1][0], i[1][1]
  166. for _ in range(randint(min, max)):
  167. ret += choice(chars)
  168. elif i[0] == 'branch':
  169. ret += choice(list(chain.from_iterable(_gen(list(x), limit) for x in i[1][1])))
  170. elif i[0] == 'subpattern':
  171. ret += _randone(i[1][1], limit)
  172. elif i[0] == 'at':
  173. continue
  174. elif i[0] == 'not_literal':
  175. c=list(CATEGORIES['category_any'])
  176. c.remove(chr(i[1]))
  177. ret += choice(c)
  178. else:
  179. #print('[!] cannot handle expression "%s"' % str(i))
  180. raise Exception('[!] cannot handle expression "%s"' % str(i))
  181. return ret
  182. def parse(s):
  183. """Regular expression parser
  184. :param s: Regular expression
  185. :type s: str
  186. :rtype: list
  187. """
  188. r = sre_parse.parse(s)
  189. return list(r)
  190. def generate(s, limit=20):
  191. """Creates a generator that generates all matching strings to a given regular expression
  192. :param s: Regular expression
  193. :type s: str
  194. :param limit: Range limit
  195. :type limit: int
  196. :returns: string generator object
  197. """
  198. return _gen(parse(s), limit)
  199. def count(s, limit=20):
  200. """Counts all matching strings to a given regular expression
  201. :param s: Regular expression
  202. :type s: str
  203. :param limit: Range limit
  204. :type limit: int
  205. :rtype: int
  206. :returns: number of matching strings
  207. """
  208. return _gen(parse(s), limit, count=True)
  209. def getone(regex_string, limit=20):
  210. """Returns a random matching string to a given regular expression
  211. """
  212. return _randone(parse(regex_string), limit)
  213. def argparser():
  214. import argparse
  215. from sys import stdout
  216. argp = argparse.ArgumentParser(description='exrex - regular expression string generator')
  217. argp.add_argument('-o', '--output'
  218. ,help = 'Output file - default is STDOUT'
  219. ,metavar = 'FILE'
  220. ,default = stdout
  221. ,type = argparse.FileType('w')
  222. )
  223. argp.add_argument('-l', '--limit'
  224. ,help = 'Max limit for range size - default is 20'
  225. ,default = 20
  226. ,action = 'store'
  227. ,type = int
  228. ,metavar = 'N'
  229. )
  230. argp.add_argument('-c', '--count'
  231. ,help = 'Count matching strings'
  232. ,default = False
  233. ,action = 'store_true'
  234. )
  235. argp.add_argument('-r', '--random'
  236. ,help = 'Returns a random string that matches to the regex'
  237. ,default = False
  238. ,action = 'store_true'
  239. )
  240. argp.add_argument('-d', '--delimiter'
  241. ,help = 'Delimiter - default is \\n'
  242. ,default = '\n'
  243. )
  244. argp.add_argument('-v', '--verbose'
  245. ,action = 'store_true'
  246. ,help = 'Verbose mode'
  247. ,default = False
  248. )
  249. argp.add_argument('regex'
  250. ,metavar = 'REGEX'
  251. ,help = 'REGEX string'
  252. )
  253. return vars(argp.parse_args())
  254. def __main__():
  255. from sys import exit, stderr
  256. # 'as(d|f)qw(e|r|s)[a-zA-Z]{2,3}'
  257. # 'as(QWE|Z([XC]|Y|U)V){2,3}asdf'
  258. # '.?'
  259. # '.+'
  260. # 'asdf.{1,4}qwer{2,5}'
  261. # 'a(b)?(c)?(d)?'
  262. # 'a[b][c][d]?[e]?
  263. args = argparser()
  264. if args['verbose']:
  265. args['output'].write('%r%s' % (parse(args['regex'], limit=args['limit']), args['delimiter']))
  266. if args['count']:
  267. args['output'].write('%d%s' % (count(args['regex'], limit=args['limit']), args['delimiter']))
  268. exit(0)
  269. if args['random']:
  270. args['output'].write('%s%s' % (getone(args['regex'], limit=args['limit']), args['delimiter']))
  271. exit(0)
  272. try:
  273. g = generate(args['regex'], args['limit'])
  274. except Exception, e:
  275. print >> stderr, '[!] Error: ', e
  276. exit(1)
  277. for s in g:
  278. try:
  279. args['output'].write(s+args['delimiter'])
  280. except:
  281. break
  282. if __name__ == '__main__':
  283. __main__()