python Regex

來源:互聯網
上載者:User

標籤:尋找   列表   分行符號   包括   HERE   you   class   索引   多行   

#! /usr/bin/env python
# -*- coding:utf-8 -*-
import re
# Regex:re模組
# 1.一般字元:大多數字元和字母都會跟自身匹配
# re.fiandall() 返回一個列表

#2.元字元:
# . 萬用字元 一個只能匹配一個結果
# ^ 以xx開頭的匹配
# $ 以xx為結尾的
# * 重複 匹配0到多次
# + 重複 匹配1到多次
# ? 匹配0到1次
# {m,n} 匹配前一個元字元m到n次
# \\ 逸出字元 其後字元失去特殊元字元含義
#[] 字元集 可匹配任意一個字元
# | 或 邏輯運算式
# \d = [0-9] 匹配一個數字
# \D = [^0-9] 匹配非數字
# \s 匹配任意空白字元
# \S 匹配非空白字元
# \w =[a-zA-Z_] 匹配數字、字母、底線中任意一個字元
# \W 匹配非數字、字母、底線中的任一字元

#3.模式
# I 忽略大小寫入模式
# L 字元集本地化
# M 多行模式
# S 此模式下.可匹配包括分行符號在內的任一字元
# X 冗餘模式 忽略運算式中的空白和注釋

# findall(pattern, string, flags=0)
str = "WoshiZhongGuoRen"
regex0 = re.findall("guo",str)
regex1 = re.findall("guo",str,re.I)
print(regex0)
print(regex1)


str1 = ‘‘‘where are you
I an here
oh I see‘‘‘

index0 = re.findall("^\w+",str1)
index1 = re.findall("^\w+",str1,re.M)
print(index0)
print(index1)

#4.函數
#郵箱Regex
#compile(pattern, flags=0) 使用 compile 函數先行編譯出一個正則模式之後再去使用,這樣在後面的代碼中可以很方便的複用它
#編譯其實是很費時的,這樣可以提升效率
str2 = "23223whh./#[email protected]"
emailregex = re.compile("[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}")
index2 = emailregex.findall(str2)
print(index2)#[‘[email protected]‘]

#match(pattern, string, flags=0)
# 使用指定正則去待操作字串中尋找可以匹配的子串, 返回匹配上的第一個字串,並且不再繼續找
#從字串開始處開始尋找的,如果開始處不匹配,則不再繼續尋找,找不到時返回 None
index3 = emailregex.match(str2)
print(index3)#None

#search(pattern, string, flags=0)
#不限制Regex的開始匹配位置
index4 = emailregex.search(str2)
print(index4)#<_sre.SRE_Match object; span=(12, 27), match=‘[email protected]‘>

#split(pattern, string, maxsplit=0, flags=0)
#maxsplit 指定切分次數
#函數使用給定Regex尋找切分字串位置,返回包含切分後子串的列表
# 如果匹配不到,則返回包含原字串的一個列表
index5 =emailregex.split(str2)
print(index5)#[‘23223whh./#$‘, ‘rtdfd‘]

#sub(pattern, repl, string, count=0, flags=0)
#將Regex pattern 匹配到的字串替換為 repl 指定的字串
#參數 count 用於指定最大替換次數
index6 = emailregex.sub(‘world‘,str2)
print(index6)#23223whh./#$worldrtdfd

#5.組(組與Match對象是Python正則式的重點)
#(?P<name>...) 分組的命名模式,取此分組中的內容時可以使用索引也可以使用name
#(?P=name) 分組的參考模式,可在同一個Regex用引用前面命名過的正則
str3 = "tom 19 05317652"
p=re.compile(r‘(?P<name>[a-z]+)\s+(?P<age>\d+)\s+(?P<tel>\d+).*‘, re.I)
p.groupindex
index7 = p.match(str3)
print(index7)
print(index7.group())
print(index7.group(‘age‘))

python Regex

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.