网络编程
位置:首页>> 网络编程>> Python编程>> Python利用正则表达式从字符串提取数字

Python利用正则表达式从字符串提取数字

作者:Buer_zhu  发布时间:2021-03-22 22:52:39 

标签:python,正则表达式,提取

前言

正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。

Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。

re 模块使 Python 语言拥有全部的正则表达式功能。

利用正则表达式从字符串提取数字

主要用到下面几个函数

(1)compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。

语法格式为:

re.compile(pattern[, flags])

参数:

  • pattern : 一个字符串形式的正则表达式

  • flags 可选,表示匹配模式,比如忽略大小写,多行模式等,具体参数为:

  • re.I 忽略大小写

  • re.L 表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境

  • re.M 多行模式

  • re.S 即为' . '并且包括换行符在内的任意字符(' . '不包括换行符)

  • re.U 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库

  • re.X 为了增加可读性,忽略空格和' # '后面的注释

(2)re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

函数语法:

re.match(pattern, string, flags=0)

(3)re.search 扫描整个字符串并返回第一个成功的匹配。

函数语法:

re.search(pattern, string, flags=0)

注:

re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

(4)findall

在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

注意: match 和 search 是匹配一次 findall 匹配所有。

语法格式为:

findall(string[, pos[, endpos]])

参数:

string 待匹配的字符串。
pos 可选参数,指定字符串的起始位置,默认为 0。
endpos 可选参数,指定字符串的结束位置,默认为字符串的长度。

下面是实现的具体方法:

def findnum(string):
   comp=re.compile(-?[1-9]\d*)
   list_str=comp.findall(string)
   list_num=[]
   for item in list_str:
       item=int(item)
       list_num.append(item)
   return list_num

re.compile()的一些匹配参数:

  • [1-9]\d*     正整数

  • -[1-9]\d*  负整数

  • -?[1-9]\d*整数

  • [1-9]\d*|0 非负整数

  • -[1-9]\d*|0 非正整数

  • [1-9]\d*\.\d*|0\.\d*[1-9]\d*$ 正浮点数

  • -([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ 负浮点数

  • -?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$ 浮点数

附python正则表达式抽取文本中的时间日期

使用python的正则表达式抽取文本中的年月日信息,如2020年5月19日。

def find_time(yanbao_txt, entity):
   paras = [para.strip() for para in yanbao_txt.split('\n') if para.strip()][:5]
   for para in paras:
       ret = re.findall(r'(\d{4})\s*[\./年-]\s*(\d{1,2})\s*[\./月-]\s*(\d{1,2})\s*日?', para)
       if ret:
           year, month, day = ret[0]
           time = '{}/{}/{}'.format(year, month.lstrip(), day.lstrip())
           return time
   return None

来源:https://blog.csdn.net/Buer_zhu/article/details/79636619

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com