homer512 icon

subxy

homer512 | PRO | 05/11/14 07:25:35 AM UTC | 0 ⭐ | 746 👁️ | Never ⏰ | []
Python |

1.92 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/python2
 
# Copyright 2014 Florian Philipp
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
 
import re
 
def subxy(string, originals, replacements, flags = 0):
    """Replaces all occurrences of originals in string with replacements
 
    Each original will be replaced with the replacement of the same index
 
    Arguments:
    string -- str or unicode to search and replace
    originals -- iterable of strings to search for
    replacements -- sequence of strings to replace originals. Has to have the
                    same length as originals
    flags -- regex flags. See re.compile. Only re.IGNORECASE is of real
             interest at the moment
    """
    escaped = [re.escape(orig) for orig in originals]
    inner_pattern = str.join(')|(', escaped)
    pattern = str.join('', ('(', inner_pattern, ')'))
    regex = re.compile(pattern, flags)
    def pick_replace(match):
        """Identifies the first matching group and selects that replacement"""
        groups = match.groups()
        nonempty = [index for index, group in enumerate(groups)
                    if group is not None]
        return replacements[nonempty[0]]
    return re.sub(regex, pick_replace, string)
    
 
def main():
    test_string = 'Foo bar baz quz bar'
    origs = ('bar', 'quz')
    repls = ('BAR', 'QUZ')
    replaced = subxy(test_string, origs, repls)
    print replaced
 
if __name__ == '__main__':
    main()

Comments