stephen杜 发表于 2022-4-7 20:33:44

正则表达式,求助 大神!!

strip()的正则表达式版本:

写一个函数,它接受一个字符串,做的事情和 strip()字符串方法一样。如果只
传入了要去除的字符串,没有其他参数,那么就从该字符串首尾去除空白字符。否
则,函数第二个参数指定的字符将从该字符串中去除。

塔利班 发表于 2022-4-7 22:05:21

ababa去除aba你的结果是啥

isdkz 发表于 2022-4-8 12:45:03

本帖最后由 isdkz 于 2022-4-8 12:47 编辑

import re

def test(s, default = 1):
    if default == 1:
      p = r'\s'
    else:
      p = re.escape(default)
    return re.sub(f"\A(?:{p})*|(?:{p})*\Z", '', s)
                                             
print("test1:", repr(test("   asxd   ")))
print("test2:", repr(test('''
   asxd   
   ''')))
print("test3:", repr(test("testAbuhgbnjtest", 'test')))
print("test4:", repr(test("\sAfgggh85\s", "\s")))
print("test5:", repr(test("testtest", "test")))
页: [1]
查看完整版本: 正则表达式,求助 大神!!