正規表示式,又稱規則表示式,英文名為regular expression,在**中常簡寫為regex、regexp或re,是電腦科學的乙個概念。正則表通常被用來檢索、替換那些符合某個模式(規則)的文字。 python 中正規表示式使用re模組。
match() 函式試圖從字串的起始部分對模式進行匹配。如果匹配成功,就返回乙個匹配物件;如果 匹配失敗,就返回 none,匹配物件的 group()方法能夠用於顯示那個成功的匹配。
import re
m = re.match(,)
m.group()-
----
----
----
----
----
---
記住,只能對起始部分進行匹配。
import re
m = re.match(
'table',)
if m is
notnone
: m.group(
)else
:print
("can't find it")-
----
----
----
can't find it
import re
m = re.search(
'table',)
if m is
notnone
:print
(m.group())
else
:print
("can't find it")-
----
----
----
table
import re
bt='pen|on|table'
m = re.match(bt,
)if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.match(bt,
'pen on the table'
)if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.search(bt,
)if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.search(bt,
)if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.match(bt,
)if m is
notnone
:print
(m.group())
else
:print
("can't find it")-
----
----
----
can't find it
penon
table
can't find it
import re
anyend=
'.pple'
m = re.match(anyend,
)#查詢首字母後的字元
if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.search(anyend,
)#查詢首字母後的字元
if m is
notnone
:print
(m.group())
else
:print
("can't find it")-
----
----
----
import re
anyend=
'.end'
m = re.match(anyend,
'end'
)#不能匹配
if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.search(anyend,
'i like\nend'
)#換行後不能匹配
if m is
notnone
:print
(m.group())
else
:print
("can't find it")-
----
----
---can't find it
can't find it
import re
anyend=
'.end'
m = re.search(anyend,
'in the end.'
)#試試這樣
if m is
notnone
:print
(m.group())
#輸出結果的前面會有乙個空格
else
:print
("can't find it")-
----
----
--- end
下面是真假「小數點」
import re
patt314 =
'3.14'
# 表示正規表示式的點號
pi_patt =
'3\.14'
# 表示字面量的點號 (dec. point)
m = re.search(patt314,
'3.14'
)if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.search(patt314,
'3014'
)if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.search(patt314,
'3514'
)if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.search(pi_patt,
'3.14'
)if m is
notnone
:print
(m.group())
else
:print
("can't find it"
)m = re.search(pi_patt,
'3014'
)if m is
notnone
:print
(m.group())
else
:print
("can't find it")-
----
----
---3.14
3014
3514
3.14
can't find it
01 正規表示式
1.獲取這串字元中的.data前的字母和數字 受理編號 利用括號進行定位 data 表示.data前的字串 正規表示式 w data 結果 firstkeyword1 若要匹配後面.data後面?之間加乙個 如 data 正規表示式 data 結果 受理編號 string templateconte...
01 初識正規表示式
1.js 2.php str hello world,hello world,hello world,hello world.pattern world 必須引號 preg match pattern,str,result var export result array 0 world 陣列裡只有1...
python正規表示式元字元 正規表示式
字元 描述將下乙個字元標記為乙個特殊字元 或乙個原義字元 或乙個 向後引用 或乙個八進位制轉義符。例如,n 匹配字元 n n 匹配乙個換行符。序列 匹配 而 則匹配 匹配輸入字串的開始位置。如果設定了 regexp 物件的 multiline 屬性,也匹配 n 或 r 之後的位置。匹配輸入字串的結束...