h3

php程序员学习python3学习第九天

1,正则表达式  python中调用正则表达式需要使用re模块

2,正则表达式字符匹配,分为普通字符和元字符

3,普通字符: 大多数字符和字母都会和自身进行匹配

  re.findall('haha','fdsfdshahafdshaha')

4,元字符 . ^ $ * + ? {} [] | () \

. 通配符

 ^ 以什么开始

$ 以什么结束

* 贪婪匹配,匹配一个字符0到多次

+ 匹配1到多次

? 匹配0次或者1次

{} 匹配指定次数

[] 可选字符集匹配 [0-9] [a-b] [^1-9] 非1到9

#-*- coding:utf-8 -*-
#正则表达式
import re

# . 通配符
res = re.findall('haha.w','dsadsahahacwhaha(w') #一个点表示任意一个字符都可
print(res)

# ^ 字符以什么开始
res = re.findall('^hello','hellohahah') #匹配得到以hello开头,返回hello
print(res)

# $ 以什么来进行结尾
res = re.findall('hello$','fefewfwhello') #匹配到以hello结尾返回hello
print(res)

# * 贪婪匹配,匹配其前一个字符0到多次
res = re.findall('hello*','sadsahello')
print(res) #hello
res = re.findall('hello*','sadsahell')
print(res) # hell
res = re.findall('hello*','dsasdhellooooo')
print(res) #hellooooo

# + 一到多次
res = re.findall('hello+','sadsahello')
print(res) #['hello']
res = re.findall('hello+','sadsahell')
print(res) #[]

#? 匹配0次或者1次
res = re.findall('hello?','fdsfdshello')
print(res) #['hello']
res = re.findall('hello?','dsafrwwhell')
print(res) #['hell']
res = re.findall('hello?','fdsfsdhellooooo')
print(res) #['hello']

#{} 匹配指定次数
res = re.findall('hello{1}','hello')
print(res) #['hello']
res = re.findall('hello{0,2}','hellooo') #匹配0到2次 0,1,2
print(res) #['hell']
res = re.findall('hello{3}','hello')
print(res) #[]

#[] 可选字符集匹配  元字符在字符集中大部分都失去功能
res = re.findall('a[bc]d','wwwwabd') #abd,acd都可匹配
print(res) #['abd']
res = re.findall('a[bc]d','fdsddadd')
print(res) #[]

#[a-z] 匹配a到z都可 [1-9] 1到9都可
#[^1-9] 除了1到9都取到了 元字符^在字符集中作用是非的意思


#\ 反斜线后跟元字符,元字符失去特殊意义,跟其他字母,附加特殊意义
'''
\d 匹配任何十进制数,相当于[0-9]
\D 匹配任何非数字字符 相当于[^0-9]
\s 匹配任何空白字符 相当于[\t\n\r\f\v]
\S 匹配任何非空白字符 相当于[^\t\n\r\f\v]
\w 匹配任何字母数字字符 相当于[a-zA-Z0-9]
\W 匹配任何非字母数字字符 相当于[^a-zA-Z0-9]
\b 匹配一个单词边界,也就是单词和空格直接的位置
'''

 

posted @ 2017-05-24 18:54  码上平天下  阅读(150)  评论(0)    收藏  举报