Added perlReToPythonRe and perlReToReplacer and associated tests.

This commit is contained in:
Jeremy Fincher 2003-04-16 05:26:24 +00:00
parent b40431cf31
commit a11f302c9d
2 changed files with 51 additions and 0 deletions

View File

@ -37,6 +37,7 @@ from __future__ import generators
from fix import *
import re
import string
import sgmllib
import htmlentitydefs
@ -198,4 +199,32 @@ def dqrepr(s):
"""Returns a repr() of s guaranteed to be in double quotes."""
return '"' + repr("'\x00" + s)[6:]
nonEscapedSlashes = re.compile(r'(?<!\\)/')
def perlReToPythonRe(s):
(kind, regexp, flags) = nonEscapedSlashes.split(s)
regexp = regexp.replace('\\/', '/')
if kind not in ('', 'm'):
raise ValueError, 'Invalid kind: must be in ("", "m")'
flag = 0
try:
for c in flags.upper():
flag &= getattr(re, c)
except AttributeError:
raise ValueError, 'Invalid flag: %s' % c
return re.compile(regexp, flag)
def perlReToReplacer(s):
(kind, regexp, replace, flags) = nonEscapedSlashes.split(s)
if kind != 's':
raise ValueError, 'Invalid kind: must be "s"'
g = False
if 'g' in flags:
g = True
flags = filter('g'.__ne__, flags)
r = perlReToPythonRe('/'.join(('', regexp, flags)))
if g:
return lambda s: r.sub(replace, s)
else:
return lambda s: r.sub(replace, s, 1)
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:

View File

@ -109,3 +109,25 @@ class UtilsTest(unittest.TestCase):
self.assertEqual(r, utils.dqrepr(s))
self.assertEqual(s, eval(utils.dqrepr(s)))
def testPerlReToPythonRe(self):
r = utils.perlReToPythonRe('m/foo/')
self.failUnless(r.search('foo'))
r = utils.perlReToPythonRe('/foo/')
self.failUnless(r.search('foo'))
r = utils.perlReToPythonRe('m/\\//')
self.failUnless(r.search('/'))
def testPerlReToReplacer(self):
f = utils.perlReToReplacer('s/foo/bar/')
self.assertEqual(f('foobarbaz'), 'barbarbaz')
f = utils.perlReToReplacer('s/fool/bar/')
self.assertEqual(f('foobarbaz'), 'foobarbaz')
f = utils.perlReToReplacer('s/foo//')
self.assertEqual(f('foobarbaz'), 'barbaz')
f = utils.perlReToReplacer('s/ba//')
self.assertEqual(f('foobarbaz'), 'foorbaz')
f = utils.perlReToReplacer('s/ba//g')
self.assertEqual(f('foobarbaz'), 'foorz')
f = utils.perlReToReplacer('s/ba\\///g')
self.assertEqual(f('fooba/rba/z'), 'foorz')