服务报价 | 域名主机 | 网络营销 | 软件工具| [加入收藏]
 热线电话: #
当前位置: 主页 > 开发教程 > python教程 >

Python re模块记录

时间:2016-01-17 18:40来源:未知 作者:最模板 点击:
re 模块 match import reexample = 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) # Helloprint m.gr

re 模块

match

import 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()

findall

import re
example = "Hello World, I am 24 years old."
pattern = re.compile(r"\d+")
m = pattern.findall(example)
print m # ['24']

sub

import 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)
(责任编辑:最模板)
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
栏目列表
热点内容