Python正則表達(dá)式如何匹配特殊字符串
Python正則表達(dá)式匹配特殊字符串
匹配特殊的字符串
匹配字符串中特定格式的字符串, 在一串字符串中,先找到特殊規(guī)則的substring, 然后再提取相關(guān)的位置value
strings = ['result-2023-08-18-6g1s1ch-DB9909', 'result-2023-08-18-4g1s3ch-DB9909', 'result-2023-08-18-1g4s1ch-DB9909', 'result-2023-08-18-1g1s1ch-DB9909'] pattern = r'(\d+)([Gg])(\d+)([Ss])(\d+)([Cc][Hh])' results = [] for s in strings: match = re.search(pattern, s) if match: print(match.group()) g = match.group(2) #匹配第2個(gè)括號(hào)的內(nèi)容 s = match.group(4) #匹配第4個(gè)括號(hào)的內(nèi)容 ch = match.group(6) #匹配第6個(gè)括號(hào)的內(nèi)容 string = match.group(1) + g + match.group(3) + s + match.group(5) + ch results.append(string) print(results) db_pattern = r'([Dd][Bb])(\d+)' match = re.search(db_pattern, strings[0]) if match: print(match.group()) db = match.group(1) #匹配第2個(gè)括號(hào)的內(nèi)容 number = match.group(2) #匹配第4個(gè)括號(hào)的內(nèi)容 db_number = db + number
輸出內(nèi)容
6g1s1ch
4g1s3ch
1g4s1ch
1g1s1ch
['6g1s1ch', '4g1s3ch', '1g4s1ch', '1g1s1ch']
DB9909
提取特殊的字符串
fullDump_pDevice00000286923A19B0_frame000_1g1s1ch.gfxbench_inst2_F535
pDevice
后面可能是一串其他數(shù)字和字母,只需要截取從frame001
開始的字符串,如:
frame000_1g1s1ch.gfxbench_inst2_F535
import re s = "fullDump_pDevice00000286923A19B0_frame000_1g1s1ch.gfxbench_inst2_F535" # Match the prefix to remove prefix_pattern = r'^fullDump_pDevice\d+_' # Use sub() to remove the matched prefix result = re.sub(prefix_pattern, '', s) print(result)
上述正則表達(dá)式并不能準(zhǔn)確替換掉,輸出結(jié)果還是原來的字符串:
fullDump_pDevice00000286923A19B0_frame000_1g1s1ch.gfxbench_inst2_F535
后使用如下表達(dá)式:
s = "fullDump_pDevice0000028fd3B19D0_frame000_1g1s1ch.gfxbench_inst2_F535" prefix_pattern = r'^fullDump_pDevice(\d+)([A-Za-z0-9]+)_' new = re.sub(prefix_pattern, "", s) print(new)
輸出結(jié)果:
frame000_1g1s1ch.gfxbench_inst2_F535
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
ubuntu17.4下為python和python3裝上pip的方法
今天小編就為大家分享一篇ubuntu17.4下為python和python3裝上pip的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06使用Python爬了4400條淘寶商品數(shù)據(jù),竟發(fā)現(xiàn)了這些“潛規(guī)則”
這篇文章主要介紹了使用Python爬了4400條淘寶商品數(shù)據(jù),竟發(fā)現(xiàn)了這些“潛規(guī)則”,筆者用 Python 爬取淘寶某商品的全過程,并對(duì)商品數(shù)據(jù)進(jìn)行了挖掘與分析,最終得出結(jié)論。需要的朋友可以參考下2018-03-03如何將Pycharm中Terminal使用Powershell作為終端
這篇文章主要介紹了如何將Pycharm中Terminal使用Powershell作為終端問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05peewee創(chuàng)建連接前的前置操作wireshark抓包實(shí)現(xiàn)
這篇文章主要為大家介紹了peewee創(chuàng)建連接前的前置操作wireshark?抓包實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10Python Django中的STATIC_URL 設(shè)置和使用方式
這篇文章主要介紹了Python Django中的STATIC_URL 設(shè)置和使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03