re 模块matchimport re example = "Hello World, I am 24 years old." pattern = re.compile(r"(\S+) (\S+) (\S*) (\S+) (\d+) (\S+) (\S+)") m = pattern.match(example) print m.group(0) # Hello World, I am 24 years old. print m.group(1) # Hello print m.group(2) # World or m = re.match(r'(\S+) (\S+) (\S*) (\S+) (\d+) (\S+) (\S+)', example) print m.group() findallimport re example = "Hello World, I am 24 years old." pattern = re.compile(r"\d+") m = pattern.findall(example) print m # ['24'] subimport re example = "Hello World, I am 24 years old." m = re.sub(r"\d+", "48", example) print m or import re example = "Hello World, I am 24 years old." m = re.sub(r"(\d+)", lambda x: "[" + x.group(1) + "]", example) print m # Hello World, I am [24] years old. or def my_replace(match): return "[" + match.group(1) + "]" m = re.sub(r"(\d+)", my_replace, example)(责任编辑:最模板) |