home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Demo / comparisons / regextest.py < prev    next >
Text File  |  1996-11-27  |  1KB  |  51 lines

  1. #! /usr/bin/env python
  2.  
  3. # 1)  Regular Expressions Test
  4. #     Read a file of (extended per egrep) regular expressions (one per line), 
  5. #     and apply those to all files whose names are listed on the command line.
  6. #     Basically, an 'egrep -f' simulator.  Test it with 20 "vt100" patterns
  7. #     against a five /etc/termcap files.  Tests using more elaborate patters
  8. #     would also be interesting.  Your code should not break if given hundreds
  9. #     of regular expressions or binary files to scan.  
  10.  
  11. # This implementation:
  12. # - combines all patterns into a single one using ( ... | ... | ... )
  13. # - reads patterns from stdin, scans files given as command line arguments
  14. # - produces output in the format <file>:<lineno>:<line>
  15. # - is only about 2.5 times as slow as egrep (though I couldn't run
  16. #   Tom's test -- this system, a vanilla SGI, only has /etc/terminfo)
  17.  
  18. import string
  19. import sys
  20. import regex
  21. from regex_syntax import *
  22.  
  23. regex.set_syntax(RE_SYNTAX_EGREP)
  24.  
  25. def main():
  26.     pats = map(chomp, sys.stdin.readlines())
  27.     bigpat = '(' + string.joinfields(pats, '|') + ')'
  28.     prog = regex.compile(bigpat)
  29.     
  30.     for file in sys.argv[1:]:
  31.         try:
  32.             fp = open(file, 'r')
  33.         except IOError, msg:
  34.             print "%s: %s" % (file, msg)
  35.             continue
  36.         lineno = 0
  37.         while 1:
  38.             line = fp.readline()
  39.             if not line:
  40.                 break
  41.             lineno = lineno + 1
  42.             if prog.search(line) >= 0:
  43.                 print "%s:%s:%s" % (file, lineno, line),
  44.  
  45. def chomp(s):
  46.     if s[-1:] == '\n': return s[:-1]
  47.     else: return s
  48.  
  49. main()
  50.