gpt4 book ai didi

python - 开头的特殊字符与每个单词的结尾匹配[仅限正则表达式]

转载 作者:行者123 更新时间:2023-12-01 06:15:11 25 4
gpt4 key购买 nike

使用正则表达式删除每个单词开头和结尾的特殊字符的最佳解决方案是什么。

"as-df-- as-df- as-df (as-df) 'as-df' asdf-asdf) (asd-f asdf' asd-f' -asdf- %asdf%s asdf& $asdf$ +asdf+ asdf++ asdf''"

输出应该是:

"as-df-- as-df- as-df (as-df) as-df asdf-asdf) (asd-f asdf' asd-f' asdf %asdf%s asdf& asdf asdf asdf++ asdf''"

如果开头的特殊字符与结尾匹配,则将其删除

我正在学习正则表达式。[仅限正则表达式]

最佳答案

import re
a = ("as-df-- as-df- as-df (as-df) 'as-df' asdf-asdf) (asd-f"
"asdf' asd-f' -asdf- %asdf%s asdf& $asdf$ +asdf+ asdf++ asdf''")
b = re.sub(r"((?<=\s)|\A)(?P<chr>[-()+%&'$])([^\s]*)(?P=chr)((?=\s)|\Z)",r"\3",a)
print b

给予:

as-df-- as-df- as-df (as-df) as-df asdf-asdf) (asd-f
asdf' asd-f' asdf %asdf%s asdf& asdf asdf asdf++ asdf''

让不同的字符起作用是个骗子 ()[]{}

关于python - 开头的特殊字符与每个单词的结尾匹配[仅限正则表达式],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3611139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com