Python——正则表达式(1)

# -*- coding:Utf-8 -*-
#导入re模块
import re
#re.match匹配以XXX开头的字符串
#具体操作 re.match("正则表达式",“字符串”)
name = "hello world"
result = re.match("h",name)
print result.group()
#结果是h

#表示单个字符的匹配字符的匹配

#.表示匹配所有 任何开头的字符串
a = "1Hh"
b = "H1h"
c = "h1H"

result = re.match(".",a)
print  "以.匹配字符"+result.group()
result = re.match(".",b)
print  "以.匹配字符"+result.group()
result = re.match(".",c)
print  "以.匹配字符"+result.group()

#[]匹配指定字符
result = re.match("[2]",a)
print result #不是以2开头 返回None
result = re.match("[1]",a)
print "[]匹配"+result.group()

#我们首先匹配a a的开头是数字可以用【0-9】l来匹配  或者\d  或者非字母
result = re.match("[0-9]",a)
result_a = re.match("\d",a)
print "使用[0-9]匹配以数字开头的字符串"+result.group()
print "使用\d匹配以数字开头的字符串:"+result_a.group()

#b开头是大写字母 1非数字 2大写字母 3字母
#1   只是为了说明  没有实际意义
result = re.match("\D",b)
print "非数字匹配字母"+result.group()

#2
result = re.match("[A-Z]",b)
print "大写字母"+result.group()

#3
result =re.match("\w",b)
print "字母"+result.group()

#匹配小写字母开头的字符串
result = re.match("[a-z]",c)
print "匹配小写字母来头的字符串"+result.group()\

d = " nihao"
result = re.match("\s",d)
print "匹配空格开头"+result.group()

result = re.match("\S",a)
print "匹配非空格开头"+result.group()

e = ".dasda"
result = re.match("\W",e)

print "匹配非单词开头"+result.group()

 

‘’‘结果

/home/python/.virtualenvs/py2/bin/python /home/python/Desktop/PY/redemo/matchDemo.pyh

以.匹配字符1

以.匹配字符H

以.匹配字符h

None

[]匹配1

使用[0-9]匹配以数字开头的字符串1

使用\d匹配以数字开头的字符串:1

非数字匹配字母H

大写字母H

字母H

匹配小写字母开头的字符串h

匹配空格开头 

匹配非空格开头1

匹配非单词开头.

Process finished with exit code 0

’‘’

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值