Py学习  »  Python

Python删除字符串开始和结束处出现的任何非字母表[重复]

lalilulelo • 4 年前 • 828 次点击  

例如:

'123foo456' --> 'foo'
'2foo1c#BAR' --> 'foo1c#BAR'

我试着用 re.sub() ,但我不能写正则表达式。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56798
 
828 次点击  
文章 [ 6 ]  |  最新文章 4 年前
Matthias
Reply   •   1 楼
Matthias    11 年前

result = re.sub('(.*?)([a-z].*[a-z])(.*)', '\\2', '23WERT#3T67', flags=re.IGNORECASE)

Martin Ender
Reply   •   2 楼
Martin Ender    11 年前

re.sub(r'^[^a-zA-Z]*(.*?)[^a-zA-Z]*$', '\1', string);

圆括号捕获字符串开头和结尾的非字母字符串之间的所有内容。这个 ? 确保 . 不在结尾捕获任何非字母字符串。然后替换者只需打印捕获的组。

Toto
Reply   •   3 楼
Toto    11 年前

要与unicode兼容:

^\PL+|\PL+$

\PL 代表 not a letter

Philip
Reply   •   4 楼
Philip    11 年前

通过您的两个示例,我可以使用Python的非贪婪语法创建regex,如前所述 here

1:[123]   2:[foo]   3:[456]
1:[2]   2:[foo1c#BAR]   3:[]

下面是正则表达式:

^([^A-Za-z]*)(.*?)([^A-Za-z]*)$

mo.group(2) 你想要什么,在哪里 mo

unutbu
Reply   •   5 楼
unutbu    11 年前

str.strip 为此:

In [1]: import string

In [4]: '123foo456'.strip(string.digits)
Out[4]: 'foo'

In [5]: '2foo1c#BAR'.strip(string.digits)
Out[5]: 'foo1c#BAR'

正如马特在评论中指出的(谢谢,马特),这只会删除数字。要删除任何非字母字符,

定义非字母的含义:

In [22]: allchars = string.maketrans('', '')

In [23]: nonletter = allchars.translate(allchars, string.letters)

然后脱掉衣服:

In [18]: '2foo1c#BAR'.strip(nonletter)
Out[18]: 'foo1c#BAR'
Wiktor Stribiżew Kent
Reply   •   6 楼
Wiktor Stribiżew Kent    4 年前

这样地?

re.sub('^[^a-zA-Z]*|[^a-zA-Z]*$','',s)

s 是输入字符串。