Learning Python 008 正則表達式-007 匹配的字符串模板中如果只有前面有字符串,而後面沒有字符串時,這個匹配模板要怎 麼寫

原博文鏈接在我的官方網站,網址是:http://www.aobosir.com/blog/2017/02/21/python-regular-expression-match-string-no-string-in-behind/


開發環境

  • Python第三方庫:lxml、Twisted、pywin32、scrapy
  • Python 版本:python-3.5.0-amd64
  • PyCharm軟件版本:pycharm-professional-2016.1.4
  • 電腦系統:Windows 10 64位

如果你還沒有搭建好開發環境,請到這篇博客


例子程序在這裏:learning_python_08_06.py

參考網站:python正則表達式詳解

Alt text

當我們的匹配字符串的末尾處沒有字符串的時候,我們使用\Z來表示結束處。

同樣的道理:當我們的匹配字符串的開頭處沒有字符串的時候,我們使用\A來表示開頭處。

# -!- coding:utf-8 -!-

import re

# Learning Python 008 正則表達式-007 匹配的字符串模板中如果只有前面有字符串,而後面沒有字符串時,這個匹配模板要怎麼寫 --- 2017年2月20日 星期一
# 博文的鏈接地址:http://www.aobosir.com/blog/2017/02/21/python-regular-expression-match-string-no-string-in-behind/

# 這個程序的功能:獲取'.\data\2017-2-19-3D-printer-hot-bed.markdown'文件裏面所有的圖片鏈接的地址。

# 這個demo 程序使用了兩次正則表達式的方式,成功的將所有的圖片鏈接地址都獲取了出來。(其中有:"![Alt text](http://www.aobosir.com/images/2017-2-21-python-regular-expression-match-string-no-string-in-behind/1485166773479.png)"這種形式的,還是"![Alt text | 240x0](http://www.aobosir.com//1485166756931.png)"這種形式的。)

file = open(r'.\data\2017-2-19-3D-printer-hot-bed.markdown', 'rt', encoding='utf-8')
data = file.read()
print(data)

image_local_path_step1 = re.findall('!\[Alt text(.*?)\)', data, re.S)
for i in range(len(image_local_path_step1)):
    print(image_local_path_step1[i])
    pass

for i in range(len(image_local_path_step1)):
    image_local_path_step1_this = image_local_path_step1[i]
    image_local_path_step2 = re.findall(']\((.*?)\Z', image_local_path_step1_this, re.S)
    print(image_local_path_step2[0])
    pass


file.close()

這個demo程序中,使用了兩層正則表達式。

第一層的匹配字符串是:!\[Alt text(.*?)\)。它可以得到](./1485164492501.png這樣或者| 240x0](./1485166756931.png這樣的結果。

解決我們將得到的結果再進行一次正則表示匹配。這次使用的匹配字符串是:]\((.*?)\Z。通過這次匹配,得到的結果就都是圖片的地址了。(想這樣:./1485181859693.png

注意:在匹配字符串中的()需要使用轉義字符\修飾。
更多精彩的博文,請訪問:http://www.aobosir.com/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章