正則表達式 java,python find 正則表達式_python正則表達式

 2023-11-19 阅读 31 评论 0

摘要:一:簡介正則表達式 java,正則表達式是處理字符串的強大工具,擁有獨特的語法和獨立的處理引擎。我們在大文本中匹配字符串時,有些情況用str自帶的函數(比如find, in)可能可以完成,有些情況會稍稍復雜一些(比如說找出所有“像郵箱”的字符串)ÿ

一:簡介

正則表達式 java,正則表達式是處理字符串的強大工具,擁有獨特的語法和獨立的處理引擎。

我們在大文本中匹配字符串時,有些情況用str自帶的函數(比如find, in)可能可以完成,有些情況會稍稍復雜一些(比如說找出所有“像郵箱”的字符串),這個時候我們需要一個某種模式的工具,這個時候正則表達式就派上用場了。

正則表達式怎么用。說起來正則表達式效率上可能不如str自帶的方法,但匹配功能實在強大太多。對啦,正則表達式不是Python獨有的,如果已經在其他語言里使用過正則表達式,這里的說明只需要簡單看一看就可以上手啦。

二:語法

python set,直接上圖:俗稱python正則表達式小抄。

[\u4e00-\u9fa5] 匹配漢字

三:python中的re模塊

Python通過re模塊提供對正則表達式的支持。

使用re的一般步驟:

將正則表達式的字符串形式編譯為Pattem實例。

使用Pattem實例處理文本并獲得匹配結果。

使用Match實例獲得信息,進行其他的操作。

importre#將正則表達式編譯成Pattern對象

pattern = re.compile('hello.*!')#使用Pattern匹配文本,獲得匹配結果,無法匹配時將返回None

match = pattern.match('hello, felix! How are you?')ifmatch:#使用Match獲得分組信息

print(match.group())#結果輸出 hello, felix!

re.compile(strPattern[, flag]):

這個方法是Pattern類的工廠方法,用于將字符串形式的正則表達式編譯為Pattern對象。

第二個參數flag是匹配模式,取值可以使用按位或運算符'|'表示同時生效,比如re.I | re.M。

當然,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)等價于re.compile('(?im)pattern')

flag可選值有:

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): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,并可以加入注釋。

#這兩句等價

regex_1 = re.compile(r"""\d + # 數字部分

\. # 小數點部分

\d * # 小數的數字部分""", re.X)

regex_2= re.compile(r"\d+\.\d*")

Match

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、\g引用分組,但不能使用編號0。\id與\g是等價的;但\10將被認為是第10個分組,如果你想表達\1之后是字符'0',只能使用\g<1>0。

importre

m= re.match(r'(\w+) (\w+)(?P.*)', 'hello felix!')print("m.string:", m.string) #m.string: hello felix!

print("m.re:", m.re) #m.re: re.compile('(\\w+) (\\w+)(?P.*)')

print("m.pos:", m.pos) #m.pos: 0

print("m.endpos:", m.endpos) #m.endpos: 12

print("m.lastindex:", m.lastindex) #m.lastindex: 3

print("m.lastgroup:", m.lastgroup) #m.lastgroup: sign

print("m.group(1,2):", m.group(1, 2)) #m.group(1,2): ('hello', 'felix')

print("m.groups():", m.groups()) #m.groups(): ('hello', 'felix', '!')

print("m.groupdict():", m.groupdict()) #m.groupdict(): {'sign': '!'}

print("m.start(2):", m.start(2)) #m.start(2): 6

print("m.end(2):", m.end(2)) #m.end(2): 11

print("m.span(2):", m.span(2)) #m.span(2): (6, 11)

print(r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3')) #m.expand(r'\2 \1\3'): felix hello!

Pattern

Pattern對象是一個編譯好的正則表達式,通過Pattern提供的一系列方法可以對文本進行匹配查找。

Pattern不能直接實例化,必須使用re.compile()進行構造。

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

pattern: 編譯時用的表達式字符串。

flags: 編譯時用的匹配模式。數字形式。

groups: 表達式中分組的數量。

groupindex: 以表達式中有別名的組的別名為鍵、以該組對應的編號為值的字典,沒有別名的組不包含在內。

importre

p= re.compile(r'(\w+) (\w+)(?P.*)', re.DOTALL)print("p.pattern:", p.pattern) #p.pattern: (\w+) (\w+)(?P.*)

print("p.flags:", p.flags) #p.flags: 48

print("p.groups:", p.groups) #p.groups: 3

print("p.groupindex:", p.groupindex) #p.groupindex: {'sign': 3}

使用pattern

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

這個方法將從string的pos下標處起嘗試匹配pattern:

如果pattern結束時仍可匹配,則返回一個Match對象

如果匹配過程中pattern無法匹配,或者匹配未結束就已到達endpos,則返回None。(從開始位置匹配,不匹配則返回)

pos和endpos的默認值分別為0和len(string)。

注意:這個方法并不是完全匹配。當pattern結束時若string還有剩余字符,仍然視為成功。想要完全匹配,可以在表達式末尾加上邊界匹配符'$'。

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

這個方法從string的pos下標處起嘗試匹配pattern

如果pattern結束時仍可匹配,則返回一個Match對象

若無法匹配,則將pos加1后重新嘗試匹配,直到pos=endpos時仍無法匹配則返回None。(掃描整個string匹配)

pos和endpos的默認值分別為0和len(string))

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):

按照能夠匹配的子串將string分割后返回列表。

maxsplit用于指定最大分割次數,不指定將全部分割。

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):

搜索string,以列表形式返回全部能匹配的子串。

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):

搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):

使用repl替換string中每一個匹配的子串后返回替換后的字符串。

當repl是一個字符串時,可以使用\id或\g、\g引用分組,但不能使用編號0。

當repl是一個方法時,這個方法應當只接受一個參數(Match對象),并返回一個字符串用于替換(返回的字符串中不能再引用分組)。 count用于指定最多替換次數,不指定時全部替換。

subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):

返回 (sub(repl, string[, count]), 替換次數)。

importreprint(re.match('super', 'superstition').span()) #(0, 5)

print(re.search('super', 'superstition').span()) #(0, 5)

print(re.match('super', 'insuperstition')) #None

print(re.search('super', 'insuperstition').span()) #(2, 7)

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

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

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

deffunc(m):return m.group(1).title() + ' ' + m.group(2).title()

p4= re.compile(r'(\w+) (\w+)')

s= 'i say, hello felix!'

print(p4.sub(r'\2 \1', s)) #say i, felix hello!

print(p4.sub(func, s)) #I Say, Hello Felix!

p5 = re.compile(r'(\w+) (\w+)')

s2= 'i say, hello felix!'

print(p5.subn(r'\2 \1', s2)) #('say i, felix hello!', 2)

print(p5.subn(func, s2)) #('I Say, Hello Felix!', 2)

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/184004.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息