日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

re库、正则表达式基本使用

發布時間:2024/1/17 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 re库、正则表达式基本使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

re庫是python的標準庫,主要用于字符串匹配。
Re庫主要功能函數

re.search()函數

re.match()函數

正則表達式

1.特殊字符

  • ^h表示以h開頭,.表示任意字符,*表示任意多次
import re line = 'hello 123' # ^h表示以h開頭,.表示任意字符,*表示任意多次 re_str = '^h.*' if re.match(re_str, line):print('匹配成功') # 輸出:匹配成功
  • $表示結尾字符
import re line = 'hello 123' re_str = '.*3$' # 前面可為任意多個任意字符,但結尾必須是3 if re.match(re_str, line):print('匹配成功') # 輸出:匹配成功
  • ?表示非貪婪模式
import re line = 'heeeello123' re_str = '.*?(h.*?l).*' # 只要()中的子串 match_obj = re.match(re_str, line) if match_obj:print(match_obj.group(1)) # 輸出:heeeel# 如果去掉?,則輸出:heeeell
  • +表示至少出現一次
import re line = 'heeeello123' re_str = '.*(h.+?l).*' match_obj = re.match(re_str, line) if match_obj:print(match_obj.group(1)) #輸出:heeeel
  • {2}表示前面字符出現2次
import re line = 'heeeello123' re_str = '.*?(e.{2}?l).*' # 匹配的是e+任意2個字符+l match_obj = re.match(re_str, line) if match_obj:print(match_obj.group(1)) # 輸出:eeel
  • | 表示或
import re line = 'hello123' re_str = '((hello|heeello)123)' match_obj = re.match(re_str, line) if match_obj:print(match_obj.group(1)) # 輸出:python123
  • []表示對單個字符給出取值范圍
import re line = 'hello123' re_str = "([jhk]ello123)" # [jhk]表示jhk中的任一個都可以 match_obj = re.match(re_str, line) if match_obj:print(match_obj.group(1)) # 輸出:hello123
  • [^]表示非字符集
import re line = 'hello123' re_str = "([^j]ello123)" # [^j]表示不是j的都行 match_obj = re.match(re_str, line) if match_obj:print(match_obj.group(1)) # 輸出:hello123
  • \s表示空格 \S表示非空格
import re line = 'hello123 好' #字符串有空格 re_str = "(hello123\s好)" # 匹配上空格 match_obj = re.match(re_str, line) if match_obj:print(match_obj.group(1)) #輸出:hello123 好
  • [\u4E00-\u9FA5]表示漢字
import re line = 'hello 北京大學' re_str = ".*?([\u4E00-\u9FA5]+大學)" match_obj = re.match(re_str, line) if match_obj:print(match_obj.group(1)) # 輸出:北京大學

小例子 提取出生日期

import re line = 'xxx出生于2000年6月1日' line = 'xxx出生于2000/6/1' line = 'xxx出生于2000-6-1' line = 'xxx出生于2000-06-01' line = 'xxx出生于2000-06' re_str = ".*出生于(\d{4}[年/-]\d{1,2}([月/-]|\d{1,2}|$))" match_obj = re.match(re_str, line) if match_obj:print(match_obj.group(1))

?

轉載于:https://www.cnblogs.com/zhang-anan/p/8496139.html

總結

以上是生活随笔為你收集整理的re库、正则表达式基本使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。