社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

lalilulelo • 5 年前 • 1645 次点击  

例如:

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

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

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

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

Martin Ender
Reply   •   2 楼
Martin Ender    12 年前

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

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

Toto
Reply   •   3 楼
Toto    12 年前

要与unicode兼容:

^\PL+|\PL+$

\PL 代表 not a letter

Philip
Reply   •   4 楼
Philip    12 年前

通过您的两个示例,我可以使用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    12 年前

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    5 年前

这样地?

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

s 是输入字符串。