如何在Python中使用正则表达式匹配任何非数字字符

如何在Python中使用正则表达式匹配任何非数字字符?

正则表达式是一组字符,允许您使用搜索模式查找一个字符串或一组字符串。RegEx是正则表达式的另一个名称。Python中的re模块用于处理正则表达式。

本文将介绍如何使用正则表达式在Python中提取非数字字符。我们使用在python中使用 \D+ 实现的正则表达式来获取字符串中的非数字字符。

其中,

  • \D 返回不包含数字的匹配项。
  • + 表示出现零次或多次的字符。

阅读更多:Python 教程

使用findall()函数

在以下示例中,我们将假设 “2018Tutorials point” 是一个字符串,我们需要消除其中的“2018”数字,并提取”Tutorials point”。

示例

在以下示例代码中,我们使用 findall() 函数使用正则表达式匹配Python中的任何非数字字符。我们首先导入正则表达式模块。

import re

然后,我们使用从re模块中导入的 findall() 函数。

import re
string = "2018Tutorials point"
pattern= [r'\D+']
for i in pattern:
match= re.findall(i, string)
print(match)

re.findall() 函数返回包含所有匹配项的列表,即具有非数字的字符串列表。

输出

执行上述程序得到以下输出。

['Tutorials point']

示例

让我们看另一个示例,字符串中有多个数字。在这里,我们假设“5 childrens 3 boys 2 girls”是一个输入短语。输出应该返回所有非数字的字符串。

import re
string = "5 childrens 3 boys 2 girls"
pattern= [r'\D+']
for i in pattern:
match= re.findall(i, string)
print(match)

输出

执行上述程序得到以下输出。

[' childrens ', ' boys ', ' girls']

使用search()函数

在以下代码中,我们匹配了 “5 childrens 3 boys 2 girls” 字符串,其中提取出所有的非数字字符字符串 “childrens boys girls”。

示例

在以下例子中,我们使用 search() 函数使用正则表达式中的正则表达式匹配Python中的任何非数字字符。我们首先导入正则表达式模块。

import re

然后,我们使用从re模块中导入的 search() 函数,以获得所需的字符串。这个 re.search() 函数搜索字符串/段落以寻找匹配项,并在有任何匹配项时返回匹配对象。使用 group() 方法返回匹配的字符串的一部分。

import re
phrase = '随机 5个孩子 3个男孩 2个女孩//'
pattern = r'(?<=随机).*?(?=//)'
match = re.search(pattern, phrase)
text = match.group(0)
nonDigit = re.sub(r'\d', '', text)
print(nonDigit)

输出结果

在执行上述程序后,会得到以下输出结果。

孩子们  男孩  女孩

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程