关于使用正则表达式从字符串中剥离非字母数字字符有几个问题。我想要做的是在第一个不是字母或单个空格(包括数字和双空格)的字符之后删除每个字符,包括字母。
例如:
My string is #not very beautiful
应该变成
My string is
或
Are you 9 years old?
应该变成
Are you
和
this is the last example
应该变成
this is the last
我该如何实现?
如何在 [^A-Za-z ]|
上拆分
并取第一个元素?您可以稍后修剪可能的空格:
import re
re.split("[^A-Za-z ]| ", "My string is #not very beautiful")[0].strip()
# 'My string is'
re.split("[^A-Za-z ]| ", "this is the last example")[0].strip()
# 'this is the last'
re.split("[^A-Za-z ]| ", "Are you 9 years old?")[0].strip()
# 'Are you'
[^A-Za-z ]|
包含两个模式,第一个模式是单个字符,既不是字母也不是空格;第二种模式是双空格;按这两种模式之一拆分,拆分后的第一个元素应该是您要查找的内容。