Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lawrencechen0921/2554d9c7711cd0e5289a895f17e58851 to your computer and use it in GitHub Desktop.
Save lawrencechen0921/2554d9c7711cd0e5289a895f17e58851 to your computer and use it in GitHub Desktop.
Regular Expression 正規表示式- 常用於字串的分析與擷取歐, 不過要先匯入模組re 假設一篇文章很長, 你想知道他出現過幾次也可以用這個方法也可以使用下一個Couter模組計算
import re #匯入模組 #這個符號是python拿來解釋用的歐
s='君不見黃河之水天上來,奔流到海不復回。\
君不見高堂明鏡悲白髮,朝如青絲暮成雪。
人生得意須盡歡,莫使金樽空對月。\
天生我材必有用,千金散盡還復來。\
烹羊宰牛且爲樂,會須一飲三百杯。\
岑夫子,丹丘生。將進酒,杯莫停。\
與君歌一曲,請君爲我側耳聽。\
鐘鼓饌玉不足貴,但願長醉不願醒。\
古來聖賢皆寂寞,惟有飲者留其名。\
陳王昔時宴平樂,斗酒十千恣讙謔。\
主人何為言少錢?徑須沽取對君酌。\
五花馬,千金裘。呼兒將出換美酒,與爾同銷萬古愁。'
print(s)
ans=re.match('君不見',s) #re模組的match去找開頭符合pattern的格式,找不到則回傳none
if ans:
print(ans.group())
else:
print("找不到【君不見】")
ans=re.search('將進酒',s) #re模組的search去找string中第一個符合pattern的格式
if ans:
print(ans.group())
else:
print("找不到【將進酒】")
ans=re.findall('五花馬',s) #re模組的findall去找到串列 串列如['五花馬'] 須為括號內這樣
if ans:
print(ans.group())
else:
print("找不到【五花馬】")
ans=re.split(',',s) #re模組的split為隔開的意思,我用逗點去分割每個句子
print(ans)
ans=re.sub('。',';',s) #re模組的sub為替換的意思(Subtitution),我用分號代替句點(記得是用後面取代前面歐)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment