mirror of
https://github.com/Mikaela/Limnoria.git
synced 2024-11-23 11:09:23 +01:00
Added perlReToPythonRe and perlReToReplacer and associated tests.
This commit is contained in:
parent
b40431cf31
commit
a11f302c9d
29
src/utils.py
29
src/utils.py
@ -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:
|
||||
|
@ -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')
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user