Pyhton 正则替换字符串指定内容

[top]

Pyhton 正则替换字符串指定内容

1. 说明

正则表达式的Sub模块,只能能提供正常全匹配,并进行替换。但有时我们需要精确匹配的时候就有点不太适用,比如: ‘my_friend and my_friendship ‘,我z只是想替换掉 my_friend 的时候,可以使用正则 r’(my_friend)\W’ 的检索来精确找到 ‘my_friend’,但如果我们要替换 ‘my_friend’ 呢? re.sub 会将 'my_friend ’ 全部替换掉,这里提供了一种通过索引找到目标并精确匹配的方法。

2. 场景

# -*- coding: utf-8 -*-

import re


class MyFriend:

    @staticmethod
    def normal_code(t_str, code, val):
        """
        :param t_str: str
        :param code: str
        :param val: str
        """
        try:
            regex = re.compile(r'(%s)' % code)
            n_str = regex.sub(val, t_str)
            return n_str

        except Exception as e:
            print('Error: %s' % e)


if __name__ == "__main__":
    stand_str = 'my_friend and my_friendship '
    aim_str = 'my_friend'
    my_friend = MyFriend()
    new_friend = my_friend.normal_code(stand_str, aim_str, '000000')
    print('== new_friend ==: %s' % new_friend)
        

执行结果:== new_friend ==: 000000 and 000000ship

3. 解决方法

通过切割字符创并在此拼接的方法,实现指定替换

# -*- coding: utf-8 -*-

import re


class MyFriend:

    @staticmethod
    def normal_code(t_str, code, val, d_index):
        """
        :param t_str: str
        :param code: str
        :param val: str
        :param d_index: int
        """
        try:
            regex = re.compile(r'(%s)\W' % code)
            while True:
                my_search = regex.search(t_str)
                if not my_search:
                    break
                aim_index = my_search.span()
                t_str = ''.join([:t_str[aim_index[0]], val, t_str[:aim_index[1]-d_index]])
            return t_str

        except Exception as e:
            print('Error: %s' % e)


if __name__ == "__main__":
    stand_str = 'my_friend and my_friendship '
    aim_str = 'my_friend'
    my_friend = MyFriend()
    new_friend = my_friend.normal_code(stand_str, aim_str, '000000', 1)
    print('== new_friend ==: %s' % new_friend)
        

执行结果:== new_friend ==: 000000 and my_friendship

猜你喜欢

转载自blog.csdn.net/qq_40601372/article/details/100745843