Python基礎知識 正則

2022-01-16 08:35:16 字數 879 閱讀 4629

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

2)正則字串,注意特殊字元轉義

3)re.match(正則字串,待匹配字串) 

4)列印匹配結果,如下

<_sre.sre_match object; span=(0, 114), match='> 2

process finished with exit code 0

_sect_tmpl = r"""

\[ # [

(?p[^]]+) # very permissive!

\] # ]

"""

re模組的re.verbose可以把正規表示式寫成多行,並且自動忽略空格。

你在re.x時可以用\來轉義空格,或者使用\s。另外,正則中的/是不需要轉義的。

sectcre = re.compile(_sect_tmpl, re.verbose)

mo = self.sectcre.match(value)

正則基礎知識

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 ...

正則基礎知識 斷言

size medium 一 單詞邊界的匹配 使用 b能匹配單詞邊界,在 b所在的一邊不是單詞字元,單詞字元的解釋是 w能匹配的字元。例如 print re.findall r b w b a sentence tcontains na lot of words a sentence contains...