在日常的開發中,python作為一門十分重要的語言,越來越受人們青睞,在python正規表示式使用也是十分廣泛,本篇部落格就來詳細講一講python中的正規表示式,也算複習一遍。
直接上例子,通俗易懂
import re
content =
'hello 123 4567 world_this is a regex demo'
result = re.match(
'^hello.*demo$'
, content)
print
(result)
print
(result.group())
print
(result.span(
))
結果
<_sre.sre_match object; span=(0, 41), match='hello 123 4567 world_this is a regex demo'>
hello 123 4567 world_this is a regex demo
(0, 41)
import re
content =
'hello 1234567 world_this is a regex demo'
result = re.match(
'^hello\s(\d+)\sworld.*demo$'
, content)
print
(result)
print
(result.group(1)
)print
(result.span(
))
結果
<_sre.sre_match object; span=(0, 40), match='hello 1234567 world_this is a regex demo'>
1234567
(0, 40)
import re
content =
'hello 1234567 world_this is a regex demo'
result = re.match(
'^he.*(\d+).*demo$'
, content)
print
(result)
print
(result.group(1)
)
結果
7
import re
content =
'hello 1234567 world_this is a regex demo'
result = re.match(
'^he.*?(\d+).*demo$'
, content)
print
(result)
print
(result.group(1)
)
結果
1234567
import re
content =
'''hello 1234567 world_this
is a regex demo
'''result = re.match(
'^he.*?(\d+).*?demo$'
, content, re.s)
print
(result.group(1)
)
結果
1234567
import re
content =
'price is $5.00'
result = re.match(
'price is $5.00'
, content)
print
(result)
結果
none
import re
content =
'price is $5.00'
result = re.match(
'price is \$5\.00'
, content)
print
(result)
結果
<_sre.sre_match object; span=(0, 14), match='price is $5.00'>
掃瞄整個字串並返回第乙個成功的匹配
import re
content =
'extra stings hello 1234567 world_this is a regex demo extra stings'
result = re.search(
'hello.*?(\d+).*?demo'
, content)
print
(result)
print
(result.group(1)
)
結果
1234567
搜尋字串,以列表形式返回全部能匹配的子串。
import re
html =
'''經典老歌列表
'''results = re.findall(
'\s*?()?(\w+)()?\s*?'
, html, re.s)
print
(results)
for result in results:
print
(result[1]
)
結果
[('', '一路上有你', ''), ('', '滄海一聲笑', ''), ('', '往事隨風', ''), ('', '光輝歲月', ''), ('', '記事本', ''), ('', '但願人長久', '')]
一路上有你
滄海一聲笑
往事隨風
光輝歲月
記事本但願人長久
替換字串中每乙個匹配的子串後返回替換後的字串。
import re
content =
'extra stings hello 1234567 world_this is a regex demo extra stings'
content = re.sub(
'(\d+)'
, r'\1 8910'
, content)
print
(content)
結果
extra stings hello 1234567 8910 world_this is a regex demo extra stings
python中正規表示式使用
1 正規表示式的常用操作符 操作符說明例項 表示任何單個字元 字符集,對單個字元給出取值範圍 abc 表示a b c,a z 表示a到z單個字元 非字符集,對單個字元給出排除範圍 abc 表示非a或b或c的單個字元 前乙個字元0次或無限次擴充套件 abc 表示ab abc abcc abccc等 前...
Python中正規表示式的使用
正規表示式是一種非常強大的工具,是用來對文字 字串 的匹配,搜尋的利器,一門好的語言都不可缺少這一模組,在python中,re模組就整合了所有正規表示式的功能 首先,把re模組中所有的函式和方法在此列舉一番 match,search,findall,split.sub,group,groups,co...
python中正規表示式
python中正規表示式語法與linux中的相容 檢視正規表示式 python提供re模組,包含所有正規表示式的功能。由於python的字串本身也用 轉義,所以要特別注意 s abc 001 python的字串 對應的正規表示式字串變成 abc 001 建議使用python的r字首,就不用考慮轉義的...