何爲正則表達式?
正則表達式,又稱規則表達式,英文名爲RegularExpression,在代碼中常簡寫爲regex、regexp或RE,是計算機科學的一個概念。正則表通常被用來檢索、替換那些符合某個模式(Patterns)的文本。
正則表達式是對字符串(包括普通字符(例如,a 到 z 之間的字母)和特殊字符(稱爲“元字符”))操作的一種邏輯公式,就是用事先定義好的一些特定字符、及這些特定字符的組合,組成一個“規則字符串”,這個“規則字符串”用來表達對字符串的一種過濾邏輯。正則表達式是一種文本模式,模式描述在搜索文本時要匹配的一個或多個字符串。
Find Patterns in Text(文本查找模式)
關於re的最常見用法是在文本中搜索模式
常用re.search()
在string中進行搜索,成功返回Match object, 失敗返回None, 只匹配一個
search(pattern, string, flags=0):
"""Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found."""
例子1:
import re
patterns = [ 'this', 'that' ]
text = 'Does this text match the pattern?'
for pattern in patterns:
print 'Looking for "%s" in "%s" ->' % (pattern, text),
if re.search(pattern, text):
print 'found a match!'
else:
print 'no match'
例子2:
import re
pattern='this' #AB
text='Does this text match the pattern ?'
match=re.search(pattern,text)
if match:
s = match.start()
e = match.end()
print('Found "%s" in "%s" from %d to %d("%s")' % \
(pattern,text, s, e, text[s:e]))
else:
print('No found')
參考:
[1]https://baike.sogou.com/v107588.htm?fromTitle=正則表達式
[2]https://pymotw.com/2/re/#finding-patterns-in-text