简体   繁体   English

如何使用 python 中的正则表达式删除除某些特殊字符外的所有特殊字符

[英]How to remove all special characters except for some, using regex in python

I have this string: ".#€f#$#" I want to use regex to remove all special characters at the beginning and the end and stop when i encounter the first character that's excluded,lets say the characters ["$", "€"] are excluded.我有这个字符串:".#€f#$#" 我想使用正则表达式删除开头和结尾的所有特殊字符,并在遇到第一个被排除的字符时停止,让我们说字符 ["$", " €"] 被排除在外。 the result should be "€f#$", Also.结果应该是“€f#$”,也。 i have different lists of characters that are excluded from the beginning and different at the end.我有不同的字符列表,它们从开头被排除在外,在结尾处不同。


text = "!#€f#$#"
newtext = re.sub("\W*$", "", text)


This only affects the ending characters and it removes ALL specials without exceptions这只会影响结尾字符,它会毫无例外地删除所有特殊字符

You may use您可以使用

import re
text = "!#€f#$#"
newtext = re.sub(r"^[^\w$€]+|[^\w$€]+$", "", text)
print(newtext)

See the Python demo请参阅Python 演示

Details细节

  • ^[^\w$€]+ - start of string ( ^ ) and 1 or more chars other than word chars, $ and € ( [^\w$€]+`) ^[^\w$€]+ - 字符串开头 ( ^ ) 和 1 个或多个除单词字符之外的字符$和 € ( [^\w$€]+`)
  • | - or - 或者
  • [^\w$€]+$ - 1 or more chars other than word chars, $ and € and end of string ( $`). [^\w$€]+$ - 除了单词字符、 $和 € and end of string ( $`) 之外的 1 个或多个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM