06Python爬蟲---正則表達式02之元字符

  元字符表

符號 含義
. 匹配除換行符以外的任意字符
^ 匹配字符串的開始位置
$ 匹配字符串的結束位置
* 匹配0次、1次或者多次前面的原子
? 匹配0次或1次前面的原子
+ 匹配1次或多次前面的原子
{n} 前面的原子恰好出現n次
{n,} 前面的原子至少出現了n次
{n,m} 前面的原子至少出現n次,至多出現m次
| 模式選擇符
() 模式單元符

總體來說,元字符可以分爲:任意匹配元字符、邊界限制元字符、限定符、模式選擇符、模式單元等

(1) 任意匹配元字符

例如:我們可以使用正則表達式’.python…’匹配一個’python’字符前面有1位,後面有3位格式的字符

import re

pattern = ".python..."

string = "abcdfphp345pythony_py"

result = re.search(pattern, string)

print("任意匹配元字符結果:%s" % result)

# 任意匹配元字符結果:<_sre.SRE_Match object; span=(10, 20), match='5pythony_p'>

(2) 邊界限制元字符

邊界限制符,’^’匹配字符串的開始,使用’$’匹配字符串的結束

import re
pattern1 = "^abd"  # 以abd開頭的字符串
pattern2 = "^abc"  # 以abc開頭的字符串
pattern3 = "py$"  # 以py結尾的字符串
pattern4 = "ay$"  # 以ay結尾的字符串
string = "abcdfphp345pythony_py"
result1 = re.search(pattern1, string)
result2 = re.search(pattern2, string)
result3 = re.search(pattern3, string)
result4 = re.search(pattern4, string)
print("結果1:%s" % result1)  # 結果1:None
print("結果2:%s" % result2)  # 結果2:<_sre.SRE_Match object; span=(0, 3), match='abc'>
print("結果3:%s" % result3)  # 結果3:<_sre.SRE_Match object; span=(19, 21), match='py'>
print("結果4:%s" % result4)  # 結果4:None

(3) 限定符

常見的限定符包括*、?、+、{n}、{n,}、{n,m}

import re
pattern1 = "py.*n"  # n和py中間除換行符意外的任意字符
pattern2 = "cd{2}"  # c後出現了2次d
pattern3 = "cd{3}"  # c後出現了3次d
pattern4 = "cd{2,}"  # c後至少出現了2次d
string = "abcdddfphp345pythony_py"
result1 = re.search(pattern1, string)
result2 = re.search(pattern2, string)
result3 = re.search(pattern3, string)
result4 = re.search(pattern4, string)
print("限定符結果1:%s" % result1)  # 限定符結果1:<_sre.SRE_Match object; span=(13, 19), match='python'>
print("限定符結果2:%s" % result2)  # 限定符結果2:<_sre.SRE_Match object; span=(2, 5), match='cdd'>
print("限定符結果3:%s" % result3)  # 限定符結果3:<_sre.SRE_Match object; span=(2, 6), match='cddd'>
print("限定符結果4:%s" % result4)  # 限定符結果4:<_sre.SRE_Match object; span=(2, 6), match='cddd'>

(4) 模式選擇符

模式選擇符’|’
使用模式選擇符,可以設置多個模式,匹配時,可以從中選擇任意一個模式匹配。
例如:正則表達式’python|php’中,字符串’python’和’php’均滿足匹配條件

import re
pattern = "python|php"
string = "abcdfphp345pythony_py"
result = re.search(pattern, string)
print("模式選擇符結果:%s" % result)
# 模式選擇符結果:<_sre.SRE_Match object; span=(5, 8), match='php'>

(5) 模式單元符

模式單元符(),可以使用’()’將一些原子組合成一個大原子使用,小括號括起來的部分會被當做一個整體去使用

import re
pattern1 = "(cd){1,}"  # cd至少出現一次
pattern2 = "cd{1,}"  # c字母后的d至少出現1string = "abcdcdcdcdfphp345pythony_py"
result1 = re.search(pattern1, string)
result2 = re.search(pattern2, string)
print("結果1:%s" % result1)  # 結果1:<_sre.SRE_Match object; span=(2, 10), match='cdcdcdcd'>
print("結果2:%s" % result2)  # 結果2:<_sre.SRE_Match object; span=(2, 4), match='cd'>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章