正則基礎知識 斷言

2021-09-01 10:31:51 字數 997 閱讀 2547

[size=medium]一、單詞邊界的匹配

使用\b能匹配單詞邊界,在\b所在的一邊不是單詞字元,單詞字元的解釋是\w能匹配的字元。例如:

print re.findall(r"\b\w+\b", "a sentence\tcontains\na lot of words")

# =>['a', 'sentence', 'contains', 'a', 'lot', 'of', 'words']

單詞邊界匹配的是某個位置而不是文字,這類匹配位置的元素叫做錨點,常用的錨點還有^和$

如果要匹配整個字串的起始位置,也可以匹配換行符之後的位置,最簡單的辦法是在正規表示式前加(?m)。例如:

string = "first line\nsecond line\r\nlast line"

linebeginwordregex = r"(?m)^\w+"

print re.findall(linebeginwordregex, string)

# =>['first', 'second', 'last']

^和$的替換

plaintext = "line1\nline2\nline3"

print re.sub(r"(?m)$", "

", re.sub(r"(?m)^", "", plaintext))

# => line1

line2

line3

使用r"(?m)^\s+"去除行首的空白字元,使用r"(?m)\s+$"去除行尾的空白字元

withspace = " begin\n between\t\n\nend"

beginsapceregex = r"(?m)^\s+"

trimmedleadingspace = re.sub(beginsapceregex, "", withspace)

print trimmedleadingspace

# =>

begin

between

end[/size]

正則基礎知識

g 全域性匹配 i 忽略大小寫 gi 以上組合 匹配乙個輸入或一行的開頭,a 匹配 an a 而不匹配 an a 匹配乙個輸入或一行的結尾,a 匹配 an a 而不匹配 an a 匹配前面元字元0次或多次,ba 將匹配b,ba,baa,baaa 匹配前面元字元1次或多次,ba 將匹配ba,baa,b...

基礎知識 正則

正規表示式簡介 測試字串的內的模式看字串是否符合規範,就是資料驗證 替換文字 在字串內提取子字串 正規表示式語法 一.普通字元 符號表示,前面的乙個字元至少出現一次 1 runoo b可以匹配runoob,runooob,runoooob等 符號表示,前面的乙個字元可以出現0次或者一次或者多次 0 ...

Python基礎知識 正則

import re str4 r id w w w s re.match str4,id 3aea5f99 6797 48bc 8b62 767a16d748c1 print s,type s if str s none print 1 else print 2 python正則寫法 1 匯入re ...