import re
# match方法進行匹配,從頭開始匹配。match這個函式如果成功匹配,返回的就是一個物件,如果匹配不到資料,返回的就是None
result = re.match('python','python is good')
print(result)
# group這個方法用來提取匹配到的資料
print(result.group())
注意點:
1、match從頭匹配
字元
.單個任意字元
result = re.match('.','bcd')
print(result.group())
[]匹配列舉字元的任何一位 [ ]
result = re.match('[pP]','Python')
print(result.group())
從開頭進行匹配
def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).match(string)
search(搜尋)全部,在一個字串中查詢
def 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."""
return _compile(pattern, flags).search(string)
注意點:
1、查詢整個字串
findall (查詢所有符合條件的,返回一個列表)
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
注意點:
1、將字串中所有符合要求的字元返回
2、返回的結果是一個列表型別
3、如果沒有符合條件的,返回的是一個空列表
sub(將字串中匹配正規表示式的部分替換為其他值)
def sub(pattern, repl, string, count=0, flags=0):
"""Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used."""
return _compile(pattern, flags).sub(repl, string, count)
ret = re.sub('\d{2}','19','age is 18,phone is 123',1)
print(ret)
split (根據匹配分割字串,返回分割字串組成的列表)
ret = re.split(' |,','age is 18,phone is 123')
print(ret)
import re
a='python'
b=re.match('p(.*?)n',a).group()#只匹配開頭print(b)
a='asdasd656165dsadas56166516'#只匹配一次
b=re.search('\d+',a).group()#匹配第一次數字串print(b)
a='sdad316564dadas56665465asdas5661616'##匹配所有。並返回一個列表
res =re.compile("\d+")#編譯正規表示式,適用於正規表示式較長以及多次使用
b=re.findall('\d+',a)#查詢全部數字串\D+是所有非數字print(b)
a='sdad316564dadas56665465asdas5661616'##匹配所有。並返回一個列表
res =re.compile("\d+")#編譯正規表示式,適用於正規表示式較長以及多次使用
b=re.sub(res,'+',a)#把匹配到的所有數字串都變成+號print(b)
a='sdad316564dadas56665465asdas5661616'##匹配所有。並返回一個列表
res =re.compile("\d+")#編譯正規表示式,適用於正規表示式較長以及多次使用
b=re.split(res,a)#以數字進行分割,返回一個列表print(b)