Regex(python)

來源:互聯網
上載者:User

標籤:輸出   obj   專業   lap   正則   高度   find   元組   分行符號   

Regex

Regex是用來匹配字串非常強大的工具,在其他程式設計語言中同樣有Regex的概念。就其本質而言,Regex(或 RE)是一種小型的、高度專業化的程式設計語言,(在Python中)它內嵌在Python中,並通過 re 模組實現。Regex模式被編譯成一系列的位元組碼,然後由用 C 編寫的匹配引擎執行。

#匯入 re 模組import re s = ‘nick jenny nice‘ # 匹配方式(一)b = re.match(r‘nick‘,s)q = b.group()print(q) # 匹配方式(二)# 產生Pattern對象執行個體,r表示匹配源字串a = re.compile(r‘nick‘)print(type(a))               #<class ‘_sre.SRE_Pattern‘> b = a.match(s)print(b)                     #<_sre.SRE_Match object; span=(0, 4), match=‘nick‘> q = b.group()print(q)  #被匹配的字串放在string中print(b.string)              #nick jenny nice#要匹配的字串放在re中print(b.re)                  #re.compile(‘nick‘)

  兩種匹配方式區別在於:第一種簡寫是每次匹配的時候都要進行一次匹配公式的編譯,第二種方式是提前對要匹配的格式進行了編譯(對匹配公式進行解析),這樣再去匹配的時候就不用在編譯匹配的格式。

 

匹配規則:

  .
  "." 匹配任一字元(除了\n)
  \
  "\" 逸出字元
  [...]
  "[...]" 匹配字元集

 

# "." 匹配任一字元(除了\n)a = re.match(r".","95nick")b = a.group()print(b)輸出結果:9 # [...] 匹配字元集a = re.match(r"[a-zA-Z0-9]","123Nick")b = a.group()print(b)輸出結果:1

  

  

  \d   
  匹配任何十進位數;它相當於類 [0-9]
  \D 
  匹配任何非數字字元;它相當於類 [^0-9]
  \s
  匹配任何空白字元;它相當於類 [\t\n\r\f\v]
  \S
  匹配任何非空白字元;它相當於類 [^\t\n\r\f\v]
  \w
  匹配任何字母數字字元;它相當於類 [a-zA-Z0-9]
  \W  
  匹配任何非字母數字字元;它相當於類 [^a-zA-Z0-9]

 

# \d \D 匹配數字/非數字a = re.match(r"\D","nick")b = a.group()print(b)輸出結果:n # \s \S 匹配空白/非空白字元a = re.match(r"\s"," ")b = a.group()print(b)輸出結果: # \w \W 匹配單詞字元[a-zA-Z0-9]/非單詞字元a = re.match(r"\w","123Nick")b = a.group()print(b)輸出結果:1a = re.match(r"\W","+-*/")b = a.group()print(b)輸出結果:+

  

  *
   "*" 匹配前一個字元0次或者無限次
  +
   "+" 匹配前一個字元1次或者無限次
  ?
    "?" 匹配一個字元0次或者1次

   {m} {m,n}

    {m} {m,n} 匹配前一個字元m次或者m到n次

   *? +? ??

    *? +? ?? 匹配模式變為非貪婪(儘可能少匹配字串)
# "*" 匹配前一個字元0次或者無限次a = re.match(r"[A-Z][a-z]*","Aaaaaa123")    #可以只匹配A,123不會匹配上b = a.group()print(b)輸出結果:Aaaaaaa # “+” 匹配前一個字元1次或者無限次a = re.match(r"[_a-zA-Z]+","nick")b = a.group()print(b)輸出結果:nick # “?” 匹配一個字元0次或者1次a = re.match(r"[0-8]?[0-9]","95")   #(0-8)沒有匹配上9b = a.group()print(b)輸出結果:9 # {m} {m,n} 匹配前一個字元m次或者m到n次a = re.match(r"[\w]{6,10}@qq.com","[email protected]")b = a.group()print(b)輸出結果:[email protected] # *? +? ?? 匹配模式變為非貪婪(儘可能少匹配字串)a = re.match(r"[0-9][a-z]*?","9nick")b = a.group()print(b)輸出結果:9a = re.match(r"[0-9][a-z]+?","9nick")b = a.group()print(b)輸出結果:9n

  

   ^  
   "^" 匹配字串開頭,多行模式中匹配每一行的開頭
   $
   "$" 匹配字串結尾,多行模式中匹配每一行的末尾
   \A
   \A 僅匹配字串開頭
    \Z

   \Z 僅匹配字串結尾

    \b

   \b 匹配一個單詞邊界,也就是指單詞和空格間的位置
# "^" 匹配字串開頭,多行模式中匹配每一行的開頭。li = "nick\nnjenny\nsuo"a = re.search("^s.*",li,re.M)b = a.group()print(b)輸出結果:suo # "$" 匹配字串結尾,多行模式中匹配每一行的末尾。li = "nick\njenny\nnick"a = re.search(".*y$",li,re.M)b = a.group()print(b)輸出結果:jenny # \A 僅匹配字串開頭li = "nickjennyk"a = re.findall(r"\Anick",li)print(a)輸出結果:[‘nick‘] # \Z 僅匹配字串結尾li = "nickjennyk"a = re.findall(r"nick\Z",li)print(a)輸出結果:[] # \b 匹配一個單詞邊界,也就是指單詞和空格間的位置a = re.search(r"\bnick\b","jenny nick car")b = a.group()print(b)輸出結果:nick

  

 

  

  |
  "|" 匹配左右任意一個運算式
  ab
  (ab) 括弧中運算式作為一個分組
  \<number>
  \<number> 引用編號為num的分組匹配到的字串
  (?P<key>vlaue)
  (?P<key>vlaue) 匹配到一個字典,去vlaue也可做別名
  (?P=name)
  (?P=name) 引用別名為name的分組匹配字串
# "|" 匹配左右任意一個運算式a = re.match(r"nick|jenny","jenny")b = a.group()print(b)輸出結果: jenny # (ab) 括弧中運算式作為一個分組a = re.match(r"[\w]{6,10}@(qq|163).com","[email protected]")b = a.group()print(b)輸出結果: [email protected] # \<number> 引用編號為num的分組匹配到的字串a = re.match(r"<([\w]+>)[\w]+</\1","<book>nick</book>")b = a.group()print(b)輸出結果: <book>nick</book> # (?P<key>vlace) 匹配輸出字典li = ‘nick jenny nnnk‘a = re.match("(?P<k1>n)(?P<k2>\w+).*(?P<k3>n\w+)",li)print(a.groupdict())輸出結果:{‘k2‘: ‘ick‘, ‘k1‘: ‘n‘, ‘k3‘: ‘nk‘} # (?P<name>) 分組起一個別名# (?P=name) 引用別名為name的分組匹配字串a = re.match(r"<(?P<jenny>[\w]+>)[\w]+</(?P=jenny)","<book>nick</book>")b = a.group()print(b)輸出結果: <book>nick</book>

  

模組方法介紹:

  match

   從頭匹配

  search

  匹配整個字串,直到找到一個匹配


  findall

  找到匹配,返回所有匹配部分的列表

   finditer

  返回一個迭代器

  sub

  將字串中匹配Regex的部分替換為其他值

  split

  根據匹配分割字串,返回分割字串組成的列表

 

######## 模組方法介紹 ########## match 從頭匹配 # search 匹配整個字串,直到找到一個匹配 # findall 找到匹配,返回所有匹配部分的列表# findall 加括弧li = ‘nick jenny nick car girl‘ r = re.findall(‘n\w+‘,li)print(r)#輸出結果:[‘nick‘, ‘nny‘, ‘nick‘]r = re.findall(‘(n\w+)‘,li)print(r)#輸出結果:[‘nick‘, ‘nny‘, ‘nick‘]r = re.findall(‘n(\w+)‘,li)print(r)#輸出結果:[‘ick‘, ‘ny‘, ‘ick‘]r = re.findall(‘(n)(\w+)(k)‘,li)print(r)#輸出結果:[(‘n‘, ‘ic‘, ‘k‘), (‘n‘, ‘ic‘, ‘k‘)]r = re.findall(‘(n)((\w+)(c))(k)‘,li)print(r)#輸出結果:[(‘n‘, ‘ic‘, ‘i‘, ‘c‘, ‘k‘), (‘n‘, ‘ic‘, ‘i‘, ‘c‘, ‘k‘)]  # finditer 返回一個迭代器,和findall一樣li = ‘nick jenny nnnk‘a = re.finditer(r‘n\w+‘,li)for i in a:    print(i.group()) # sub 將字串中匹配Regex的部分替換為其他值li = ‘This is 95‘a = re.sub(r"\d+","100",li)print(a) li = "nick njenny ncar ngirl"a = re.compile(r"\bn")b = a.sub(‘cool‘,li,3)      #後邊參數替換幾次print(b) #輸出結果:#coolick cooljenny coolcar ngirl # split 根據匹配分割字串,返回分割字串組成的列表li = ‘nick,suo jenny:nice car‘a = re.split(r":| |,",li)   #或|print(a) li = ‘nick1jenny2car3girl5‘a = re.compile(r"\d")b = a.split(li)print(b) #輸出結果:#[‘nick‘, ‘jenny‘, ‘car‘, ‘girl‘, ‘‘]   #注意後邊空元素

  

  group()
  返回被 RE 匹配的字串
  groups()
 
  返回一個包含Regex中所有小組字串的元組,從 1 到所含的小組號
  groupdict()
 
  返回(?P<key>vlace)定義的字典
  start()
  返回匹配開始的位置
  end()
  返回匹配結束的位置
  span()
  返回一個元組包含匹配 (開始,結束) 的索引位置
li = ‘nick jenny nnnk‘ a = re.match("n\w+",li)print(a.group()) a = re.match("(n)(\w+)",li)print(a.groups()) a = re.match("(?P<k1>n)(?P<k2>\w+).*(?P<k3>n\w+)",li)print(a.groupdict())輸出結果:nick(‘n‘, ‘ick‘){‘k1‘: ‘n‘, ‘k3‘: ‘nk‘, ‘k2‘: ‘ick‘} -----------------------------------------------import rea = "123abc456" re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0)   #123abc456,返回整體 re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1)   #123 re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2)   #abc re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3)   #456  group(1) 列出第一個括弧匹配部分,group(2) 列出第二個括弧匹配部分,group(3)列出第三個括弧匹配部分。

  

 

  

  re.I
  使匹配對大小寫不敏感
  re.L
  做本地化識別(locale-aware)匹配
  re.M
  多行匹配,影響 ^ 和 $
  re.S  
  使 . 匹配包括換行在內的所有字元
  re.U
  根據Unicode字元集解析字元。這個標誌影響 \w, \W, \b, \B.
  re.X
 
  注釋,會影響空格(無效了)
#re.I   使匹配對大小寫不敏感a = re.search(r"nick","NIck",re.I)print(a.group()) #re.L   做本地化識別(locale-aware)匹配#re.U   根據Unicode字元集解析字元。這個標誌影響 \w, \W, \b, \B. #re.S:.將會匹配分行符號,預設.逗號不會匹配分行符號a = re.findall(r".","nick\njenny",re.S)print(a)輸出結果:[‘n‘, ‘i‘, ‘c‘, ‘k‘, ‘\n‘, ‘j‘, ‘e‘, ‘n‘, ‘n‘, ‘y‘] #re.M:^$標誌將會匹配每一行,預設^只會匹配符合正則的第一行;預設$只會匹配符合正則的末行n = """12 drummers drumming,11 pipers piping, 10 lords a-leaping""" p = re.compile("^\d+")p_multi = re.compile("^\d+",re.M)print(re.findall(p,n))print(re.findall(p_multi,n))

  

常見正則列子:

匹配手機號:

# 匹配手機號phone_num = ‘13001000000‘a = re.compile(r"^1[\d+]{10}")b = a.match(phone_num)print(b.group())

  

匹配IPv4:

# 匹配IP地址ip = ‘192.168.1.1‘a = re.compile(r"(((1?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))\.){3}((1?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))$")b = a.search(ip)print(b)

  

匹配email:

# 匹配 emailemail = ‘[email protected]‘a = re.compile(r"(.*){0,26}@(\w+){0,20}.(\w+){0,8}")b = a.search(email)print(b.group())

  

 

Regex(python)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.