如何从 Python 中的字符串中删除非字母数字前缀和后缀?

How to cut non-alphanumeric prefix and suffix from a string in Python?

如何从字符串的开头和结尾截取非字母数字的所有字符?

例如:

print(clearText('%!_./123apple_42.juice_(./$)'))
# => '123apple_42.juice'

print(clearText('  %!_also remove.white_spaces(./$)   '))
# => 'also remove.white_spaces'

您可以使用这种模式:^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$

解释:

^[^a-zA-Z0-9] - 匹配字符串开头的一个或多个非字母数字字符(感谢 ^

[^a-zA-Z0-9]$ - 匹配字符串末尾的一个或多个非字母数字字符(感谢 $

|表示交替,因此匹配开头或结尾的非字母数字字符串

Demo

然后用空字符串替换匹配项就足够了。

这家伙抓取字母数字字符之间的所有内容。

import re

def clearText(s):
    return re.search("[a-zA-Z0-9].*[a-zA-Z0-9]", s).group(0)

print(clearText("%!_./123apple_42.juice_(./$)"))