python - 删除 python 字符串中第一个字符之后不是字母的所有内容

标签 python regex string

<分区>

关于使用正则表达式从字符串中剥离非字母数字字符有几个问题。我想要做的是在第一个不是字母或单个空格(包括数字和双空格)的字符之后删除每个字符,包括字母。

例如:

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 ]| 包含两个模式,第一个模式是单个字符,既不是字母也不是空格;第二种模式是双空格;按这两种模式之一拆分,拆分后的第一个元素应该是您要查找的内容。

关于python - 删除 python 字符串中第一个字符之后不是字母的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41497398/

相关文章:

python - 解码文件名问题

python - 如何处理 BigTable Scan InvalidChunk 异常?

php - 在单引号和双引号内捕获 __ ('<string>' )

python - 正则表达式在多种条件下匹配版权声明中的公司名称

c# - DateTime 到 Hex 并在不转换为 Int64 的情况下反转

python - 如何将文件列表的名称从同一文件夹中的同一numpy文件中按顺序排列?

python - 从列表中删除词典

PHP:如何获取 HTML 元素的正确结束标记

string - Scala 字符串修剪一组字符

c++ - 无法通过 is_open 和正确检查读取文本文件?