代码如下
1 import re 2 # 找到226个,抽取数字 3 total = '找到 22 6 个 ' 4 totalC = re.sub("D", "", total) 5 print('抽取出来的数字有:',totalC)
在'找到 22 6 个 '这个字符串中找到非数字的字符(正则表达式中'D'表示非数字),并用""替换,然后返回的就是只剩下数字的字符串。
在Python3.5.2 官方文档re模块中sub函数的定义是:
re.sub(pattern, repl, string, count=0, flags=0)
在字符串 string 中找到匹配正则表达式 pattern 的所有子串,用另一个字符串 repl 进行替换。如果没有找到匹配 pattern 的串,则返回未被修改的 string。Repl 既可以是字符串也可以是一个函数。