欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python 正则表达式 过滤字符串两边的字符,类似strip功能 练习题

程序员文章站 2023-12-21 15:53:52
...
import re


def customerStrip(steament, string):
    '''
    :param steament: 被过滤的字符串
    :param string: 要过滤的字符
    :return: 返回过滤后的数据
    '''
    string = '\\' + string
    customerRegex = re.compile(r'^(((' + string + ')*)?(\s*))(.*?)((\s*)?((' + string + ')*))$')
    try:
        moCustome = customerRegex.search(steament).groups()
        return moCustome[4]
    except AttributeError:
        return '不存在要过滤的字符!'


text = '####3213213###'

print(customerStrip(text, '#'))

自己练习写的很不完善。
经测试,strip 这是这个自定义函数customerStrip的80多倍,很差劲,方法写的不好
import re

import time


def leftRegex(steament, string):
    lRgex = re.compile(r'(^(' + string + ')*)')
    moLeft = lRgex.search(steament).group()
    return moLeft


def rightRegex(steament, string):
    rRegex = re.compile(r'((' + string + ')*)$')
    moRight = rRegex.search(steament).group()
    return moRight


def customerStrip(steament, string, type='center'):
    '''
    :param steament: 
    :param string: 
    :param type: 
    :return: 
    '''
    if string.isspace():
        string = '\s'
    else:
        string = '\\' + string
    if type == 'right':
        right = rightRegex(steament, string)
        return  steament[:-len(right)]
    elif type == 'left':
        left=leftRegex(steament, string)
        return steament[len(left):]
    elif type == 'center':
        right = rightRegex(steament, string)
        left = leftRegex(steament, string)
        steament =steament[:-len(right)]
        steament=steament[len(left):]
        return steament


text = '##321333333333333354343243255442343241341324312414321####'




# customer time
start = time.time()
print(customerStrip(text, '#'))
end = time.time()

time1 = end - start
# strip time
start1 = time.time()
print(text.strip('#'))
ends = time.time()
time2 = ends - start1
print(time1/time2)

此函数经测试,strip 是他的40-50倍,比上面那个提高了不少,依然很差劲

import re

import time


def customerStrip(steament, string):
    if string.isspace():
        string = '\s'
    else:
        string = '\\' + string
    centerRegex = re.compile(r'(^(' + string + ')*)?(.*?)((' + string + ')*)?$')
    result = centerRegex.search(steament).groups()[2]
    return result

和上面的差不多速度

相关标签: strip python

上一篇:

下一篇: