正则表达式(一) search
何為正則表達(dá)式?
正則表達(dá)式,又稱規(guī)則表達(dá)式,英文名為RegularExpression,在代碼中常簡(jiǎn)寫(xiě)為regex、regexp或RE,是計(jì)算機(jī)科學(xué)的一個(gè)概念。正則表通常被用來(lái)檢索、替換那些符合某個(gè)模式(Patterns)的文本。
正則表達(dá)式是對(duì)字符串(包括普通字符(例如,a 到 z 之間的字母)和特殊字符(稱為“元字符”))操作的一種邏輯公式,就是用事先定義好的一些特定字符、及這些特定字符的組合,組成一個(gè)“規(guī)則字符串”,這個(gè)“規(guī)則字符串”用來(lái)表達(dá)對(duì)字符串的一種過(guò)濾邏輯。正則表達(dá)式是一種文本模式,模式描述在搜索文本時(shí)要匹配的一個(gè)或多個(gè)字符串。
Find Patterns in Text(文本查找模式)
關(guān)于re的最常見(jiàn)用法是在文本中搜索模式
常用re.search()
在string中進(jìn)行搜索,成功返回Match object, 失敗返回None, 只匹配一個(gè)
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 repatterns = [ '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 repattern='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=正則表達(dá)式
[2]https://pymotw.com/2/re/#finding-patterns-in-text
總結(jié)
以上是生活随笔為你收集整理的正则表达式(一) search的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Win7开启无线热点AP
- 下一篇: css怎样让字体变细,css怎么把字体变