Removed some XXXes and allowed other separators than /.

This commit is contained in:
Jeremy Fincher 2004-12-16 09:22:39 +00:00
parent 5d37d71afb
commit cc084d2535
2 changed files with 32 additions and 5 deletions

View File

@ -214,16 +214,33 @@ def quoted(s):
"""Returns a quoted s."""
return '"%s"' % s
nonEscapedSlashes = re.compile(r'(?<!\\)/')
def _getSep(s):
assert len(s) >= 2
if s.startswith('m') or s.startswith('s'):
separator = s[1]
else:
separator = s[0]
if separator.isalnum() or separator in '{}[]()<>':
raise ValueError, \
'Invalid separator: separator must not be alphanumeric or in ' \
'"{}[]()<>"'
return separator
def _getSplitterRe(s):
separator = _getSep(s)
return re.compile(r'(?<!\\)%s' % re.escape(separator))
def perlReToPythonRe(s):
"""Converts a string representation of a Perl regular expression (i.e.,
m/^foo$/i or /foo|bar/) to a Python regular expression.
"""
sep = _getSep(s)
splitter = _getSplitterRe(s)
try:
(kind, regexp, flags) = nonEscapedSlashes.split(s)
(kind, regexp, flags) = splitter.split(s)
except ValueError: # Unpack list of wrong size.
raise ValueError, 'Must be of the form m/.../ or /.../'
regexp = regexp.replace('\\/', '/')
regexp = regexp.replace('\\'+sep, sep)
if kind not in ('', 'm'):
raise ValueError, 'Invalid kind: must be in ("", "m")'
flag = 0
@ -242,12 +259,14 @@ def perlReToReplacer(s):
s/foo/bar/g or s/foo/bar/i) to a Python function doing the equivalent
replacement.
"""
sep = _getSep(s)
splitter = _getSplitterRe(s)
try:
(kind, regexp, replace, flags) = nonEscapedSlashes.split(s)
(kind, regexp, replace, flags) = splitter.split(s)
except ValueError: # Unpack list of wrong size.
raise ValueError, 'Must be of the form s/.../.../'
regexp = regexp.replace('\x08', r'\b')
replace = replace.replace('\\/', '/')
replace = replace.replace('\\'+sep, sep)
for i in xrange(10):
replace = replace.replace(chr(i), r'\%s' % i)
if kind != 's':

View File

@ -177,6 +177,10 @@ class UtilsTest(SupyTestCase):
self.failUnless(r.search('CAT'))
self.assertRaises(ValueError, utils.perlReToPythonRe, 'm/?/')
def testP2PReDifferentSeparator(self):
r = utils.perlReToPythonRe('m!foo!')
self.failUnless(r.search('foo'))
def testPerlReToReplacer(self):
f = utils.perlReToReplacer('s/foo/bar/')
self.assertEqual(f('foobarbaz'), 'barbarbaz')
@ -197,6 +201,10 @@ class UtilsTest(SupyTestCase):
f = utils.perlReToReplacer('s/^/foo/')
self.assertEqual(f('bar'), 'foobar')
def testPReToReplacerDifferentSeparator(self):
f = utils.perlReToReplacer('s#foo#bar#')
self.assertEqual(f('foobarbaz'), 'barbarbaz')
def testPerlReToReplacerBug850931(self):
f = utils.perlReToReplacer('s/\b(\w+)\b/\1./g')
self.assertEqual(f('foo bar baz'), 'foo. bar. baz.')