re.match(pattern, string, flags=0) 从字符串的起始位置匹配一个模式,若是不是起始位置匹配成功的话,match()就返回none正则表达式
def test_match():
string = "hello world meili fengxin hello"
match = re.match(r"hello", string)
if match:
print(match.group(0))
re.search(pattern, string, flags=0) 扫描整个字符串并返回第一个成功的匹配app
def test_search():
string = "world meili fengxin hello"
match = re.search(r'hello', string)
if match:
print(match.group(0))
re.split(pattern, string[, maxsplit=0, flags=0])按照可以匹配的子串将字符串分割后返回列表函数
def test_split():
string = "hello world meili fengxin hello"
li = re.split(r" ", string)
for ele in li:
print(ele)
re.sub(pattern, repl, string, count=0, flags=0) 用于替换字符串中的匹配项ui
def test_sub():
string = "hello world meili fengxin hello"
new_str = re.sub(r"hello", "你好", string)
print(new_str)
findall(pattern,string,pos,endpos) 在字符串中找到正则表达式所匹配的全部子串,并返回一个列表,若是没有找到匹配的,则返回空列表spa
def test_findall():
string = "hello world meili fengxin hello"
li = re.findall(r"hello", string)
print(li)
re.finditer 在字符串中找到正则表达式所匹配的全部子串,并把它们做为一个迭代器返回code
def test_finditer():
string = "hello world meili fengxin hello hello"
it = re.finditer(r"hello", string)
for match in it:
print(match.group())
compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match()、search()、split()等上述李哥函数使用。orm
# -*- coding: UTF-8 -*-
import re
str = "hello world nihao shijie hello"
regObj = re.compile("hello")
match = regObj.match(str)
if match:
print(match.group(0))