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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

简单理解正则表达式

發布時間:2023/11/29 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 简单理解正则表达式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我理解的正則表達式:

  正則表達式就是用于字符(串)匹配時的一種描述字符串的表達式。

關于正則表達式:

預定義的字符類

  • \d可以匹配一個數字;
  • 用\D表示非數字字符[^\d]
  • \w可以匹配一個字母或數字;
  • 用\W表示非單詞字符[^\w]
  • \s表示空白字符[空格\t\n\f\v]
  • \S非空白字符[^\s]

數量詞

  • . ?可以匹配任意除換行(\n)字符;因此匹配的只能同一行的字符;再點任意匹配模式下可以匹配換行符
  • *表示任意個字符(包括0個);
  • +表示至少一個字符;
  • ?表示0個或1個字符;還可以使 +.*{n,m}數量詞變成非貪婪模式
  • {n}表示n個字符;
  • {n,m}表示n-m個字符;
  • 如‘\d+\-\w*\s{2-8}\w?描述的就是:123-a ?2或1-________(_表示空格);

字符集

  • [0-9a-zA-Z\_]可以匹配一個數字、字母或者下劃線;
  • [0-9a-zA-Z\_]+可以匹配至少由一個數字、字母或者下劃線組成的字符串,比如'a100','0_Z','Py3000'等等;
  • [a-zA-Z\_][0-9a-zA-Z\_]*可以匹配由字母或下劃線開頭,后接任意個由一個數字、字母或者下劃線組成的字符串,也就是Python合法的變量;
  • [a-zA-Z\_][0-9a-zA-Z\_]{0, 19}更精確地限制了變量的長度是1-20個字符(前面1個字符+后面最多19個字符);
  • A|B可以匹配A或B,所以(A|a)m可以匹配'Am'或者'am';

邊界匹配

  • ^表示行的開頭,^\d表示必須以數字開頭;
  • $表示行的結束,\d$表示必須以數字結束;
  • \A僅匹配字符串開頭
  • \Z僅匹配字符串末尾
  • \b匹配\w和\W之間的 ???????????????????
  • \B ? ?匹配[^\b]
  • \表示為轉義字符,在python的原生字符串r‘’里應用比較直觀方便

Python內的正則表達式運用re模塊

檢驗正則表達式最好用的函數match()

  • 判斷是否匹配,如果匹配成功,返回一個Match對象,否則返回None;
  • re模塊的匹配過程:正則表達式文本----編譯----->正則表達式對象----匹配---->待匹配文本---->匹配結果。
  • patternr =re.compile(r‘正則表達式’) ----------編譯?
  • math = pattern.match('待匹配字符串') ----------匹配
  • print match.group() ? ? ? ? ? ? ? ? ? ? ? ? ? ? ----------結果

re.compile(strPattern[, flag]):

這個方法是Pattern類的工廠方法,用于將字符串形式的正則表達式編譯為Pattern對象。 第二個參數flag是匹配模式,取值可以使用按位或運算符'|'表示同時生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)與re.compile('(?im)pattern')是等價的。?
可選值有:

  • re.I(re.IGNORECASE): 忽略大小寫
  • re.M(MULTILINE): 多行模式,改變'^'和'$'的行為
  • re.S(DOTALL): 點任意匹配模式,改變'.'的行為
  • re.L(LOCALE): 使預定字符類 \w \W \b \B \s \S 取決于當前區域設定
  • re.U(UNICODE): 使預定字符類 \w \W \b \B \s \S \d \D 取決于unicode定義的字符屬性

re.X(VERBOSE): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,并可以加入注釋。以下兩個正則表達式是等價的:

re.compile(r"""\d + # the integral part\. # the decimal point\d * # some fractional digits""", re.X)re.compile(r"\d+\.\d*")

Match

Match對象是一次匹配的結果,包含了很多關于此次匹配的信息,可以使用Match提供的可讀屬性或方法來獲取這些信息。

屬性:

  • string: 匹配時使用的文本。
  • re: 匹配時使用的Pattern對象。
  • pos: 文本中正則表達式開始搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
  • endpos: 文本中正則表達式結束搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
  • lastindex: 最后一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,將為None。
  • lastgroup: 最后一個被捕獲的分組的別名。如果這個分組沒有別名或者沒有被捕獲的分組,將為None。

方法:

  • group([group1, …]):?
    獲得一個或多個分組截獲的字符串;指定多個參數時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數時,返回group(0);沒有截獲字符串的組返回None;截獲了多次的組返回最后一次截獲的子串。
  • groups([default]):
    以元組形式返回全部分組截獲的字符串。相當于調用group(1,2,…last)。default表示沒有截獲字符串的組以這個值替代,默認為None。
  • groupdict([default]):?
    返回以有別名的組的別名為鍵、以該組截獲的子串為值的字典,沒有別名的組不包含在內。default含義同上。
  • start([group]):
    返回指定的組截獲的子串在string中的起始索引(子串第一個字符的索引)。group默認值為0。
  • end([group]):?
    返回指定的組截獲的子串在string中的結束索引(子串最后一個字符的索引+1)。group默認值為0。
  • span([group]):?
    返回(start(group), end(group))。
  • expand(template):
    將匹配到的分組代入template中然后返回。template中可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。\id與\g<id>是等價的;但\10將被認為是第10個分組,如果你想表達\1之后是字符'0',只能使用\g<1>0。
import re m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!')print "m.string:", m.string print "m.re:", m.re print "m.pos:", m.pos print "m.endpos:", m.endpos print "m.lastindex:", m.lastindex print "m.lastgroup:", m.lastgroupprint "m.group(1,2):", m.group(1, 2) print "m.groups():", m.groups() print "m.groupdict():", m.groupdict() print "m.start(2):", m.start(2) print "m.end(2):", m.end(2) print "m.span(2):", m.span(2) print r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3')### output ### # m.string: hello world! # m.re: <_sre.SRE_Pattern object at 0x016E1A38> # m.pos: 0 # m.endpos: 12 # m.lastindex: 3 # m.lastgroup: sign # m.group(1,2): ('hello', 'world') # m.groups(): ('hello', 'world', '!') # m.groupdict(): {'sign': '!'} # m.start(2): 6 # m.end(2): 11 # m.span(2): (6, 11) # m.expand(r'\2 \1\3'): world hello!

?

Pattern

Pattern對象是一個編譯好的正則表達式,通過Pattern提供的一系列方法可以對文本進行匹配查找。Pattern不能直接實例化,必須使用re.compile()進行構造。

Pattern提供了幾個可讀屬性用于獲取表達式的相關信息:

  • pattern: 編譯時用的表達式字符串。
  • flags: 編譯時用的匹配模式。數字形式。
  • groups: 表達式中分組的數量。
  • groupindex: 以表達式中有別名的組的別名為鍵、以該組對應的編號為值的字典,沒有別名的組不包含在內。
import re p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)print "p.pattern:", p.pattern print "p.flags:", p.flags print "p.groups:", p.groups print "p.groupindex:", p.groupindex### output ### # p.pattern: (\w+) (\w+)(?P<sign>.*) # p.flags: 16 # p.groups: 3 # p.groupindex: {'sign': 3}

?

實例方法

1、match(string[, pos[, endpos]]) | re.match(pattern, string[, flags])

這個方法將從string的pos下標處起嘗試匹配pattern;如果pattern結束時仍可匹配,則返回一個Match對象;如果匹配過程中pattern無法匹配,或者匹配未結束就已到達endpos,則返回None。?

>>> import re >>> re.match(r'<link rel="(.+)" href="//(.+)" />','<link rel="dns-prefetch" href="//g.alicdn.com" />') <_sre.SRE_Match object at 0x0000000002B6FE88> >>> re.match(r'<link rel="(.+)" href="//(.+)" />','<link reB="dns-prefetch" href="//g.alicdn.com" />') >>>

?

2、search(string[, pos[, endpos]]) | re.search(pattern, string[, flags])

這個方法用于查找字符串中可以匹配成功的子串。從string的pos下標處起嘗試匹配pattern,如果pattern結束時仍可匹配,則返回一個Match對象;若無法匹配,則將pos加1后重新嘗試匹配;直到pos=endpos時仍無法匹配則返回None。?
pos和endpos的默認值分別為0和len(string));re.search()無法指定這兩個參數,參數flags用于編譯pattern時指定匹配模式。

# encoding: UTF-8 import re pattern = re.compile(r'world') match = pattern.search('hello world!') print match.group() ### Output ### # world

3、split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):?
按照能夠匹配的子串將string分割后返回列表。maxsplit用于指定最大分割次數,不指定將全部分割。

p = re.compile(r'\d+') print p.split('one1two2three3four4')### output ### # ['one', 'two', 'three', 'four', '']?

4、findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):?
搜索string,以列表形式返回全部能匹配的子串。

p = re.compile(r'\d+') print p.findall('one1two2three3four4')### output ### # ['1', '2', '3', '4']

?

5、finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):?
搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。

p = re.compile(r'\d+') for m in p.finditer('one1two2three3four4'):print m.group(),### output ### # 1 2 3 4

?

6、sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):?
使用repl替換string中每一個匹配的子串后返回替換后的字符串。?
當repl是一個字符串時,可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。?
當repl是一個方法時,這個方法應當只接受一個參數(Match對象),并返回一個字符串用于替換(返回的字符串中不能再引用分組)。?
count用于指定最多替換次數,不指定時全部替換。?

p = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!'print p.sub(r'\2 \1', s)def func(m):return m.group(1).title() + ' ' + m.group(2).title()print p.sub(func, s)#此處函數func內傳入的參數為re.match的返回值
#print func(re.match(p,s)) 的輸出為I Say
#可見此處函數(sub)的執行特點相當于執行了兩次re.match
###output ### # say i, world hello! # I Say, Hello World!

?

7、subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):?
返回 (sub(repl, string[, count]), 替換次數)。

p = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!'print p.subn(r'\2 \1', s)def func(m):return m.group(1).title() + ' ' + m.group(2).title()print p.subn(func, s)### output ### # ('say i, world hello!', 2) # ('I Say, Hello World!', 2)

8、爬蟲常用的幾個函數

def getHtml(url):page = urllib.urlopen(url)html =page.read()return html def GetLink(html): # reg = r'<link rel="(.+)" href="//(.+)" />'#正則表達式模板imgre = re.compile(reg) imglist = re.findall(imgre,html) return imglist

?參考:http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

轉載于:https://www.cnblogs.com/w-smile/p/7203502.html

總結

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

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