Python 正則表達

1.match和search的區別

def re_method():
# search vs. Match
s = 'abcd'
print(re.search(r'c', s))
print(re.match(r'c', s))
if __name__ == '__main__':
re_method()

返回值爲
<_sre.SRE_Match object; span=(2, 3), match='c'>
None

match從字符串的第一個開始進行匹配,可以通過在前面加.*的方式找到,其中.表示匹配任意字符
re.match(r'.*c', s)
search:搜索字符串任意位置的匹配,可以通過添加^^表示某一字符串的開始位置
re.search(r'^c', s)

2.split

分割字符,按照非字母字符
re.split(r'\W+','I love you')

[‘I’, ‘love’, ‘you’]

\W:表示非字母字符,\w:表示字母字符,如果按照\w分割,那麼會是另一種結果

3.findall和finditer

findall根據正則表達式從左到右搜索匹配項,返回匹配的字符串列表(跟search是對應的關係,search是隻要搜索到匹配的第一個,它就會停下來,findall是會繼續往下查找)
re.findall(r'\w+','I love you')
輸出['I', 'love', 'you']

re.findall(r'\d+\.?\d*', 'The beef is $5.6,I like to take 2 piece',)
輸出[5.6 2]

finditer根據正則表達式從左到右搜索匹配項,返回一個迭代器迭代返回MatchObjec

def re_demo():
    s = 'The first price is $9.90 and the second price is $100'

    i = re.finditer(r'\d+\.?\d*', s)
    for m in i:
        print(m.group())
re_demo()

4.sub和subn

字符串替換字符串替換

s = 'The first price is $9.90 and the second price is $100'
    print(re.sub(r"\$\d+\.?\d*",'<number>',s))

subn和sub一樣:返回值多了替換的字符串個數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章