您的位置:首页 > 其它

regular

2016-06-26 15:01 176 查看
regular.py

import re

# .
# 只能匹配一个字母,而不是2个或0个

# \
# 转义
# 'abc\\.com' r'abc\.com'

# 字符集[]
# 匹配他所包括的任意字符
# '[pj]y' 匹配 'py'和 'jy'
# [a-z]  [a-zA-Z0-9]
# 反转字符集 [^abc] 匹配除了a,b,c意外的字符
# 需要转义:^出现在开头,-和]出现在末尾

# 字符串开始^
# 字符串结尾$

# 选择符,子模式 |
# 'py|abc' 匹配py 和 abc
# 'p(aaa|bbb)'

# 可选项和重复子模式
# 在子模式后加问号,变成可选项。问号表示子模式可以出现1次或不出现
# r'(http://)?(www\.)?python\.org'
# (pattern)*         重复0次,或多次
# (pattern)+         重复1次或多次
# (pattern){m,n}     重复m~n次

# re 模块重要函数
# compile,search,match,split,findall,sub,escape P194
# re.search 寻找第一个匹配的子字符串,返回True,False
# re.match 从给定字符串的开头,匹配正则表达式
m = re.match(r'\[(.*)\]', 'www[aa]cc')  # [不在开头,所以不能匹配
#[]加转义\,否则代表字符集
if m:
print(m.group(1))
m = re.match(r'.*\[(.*)\]', 'www[aa]cc')
if m:
print(m.group(1))

# re.findall 以列表,返回给定模式的所有匹配项
print(re.findall('[a-zA-Z]+', '"as...oo--as you it?"he said,fd.'))
print(re.findall(r'["\-.?]+', '"as...oo--as you it?"he said,fd.'))
print(re.findall(r'\[(.*)\]', 'www[aa]cc[,,]cc[mm0]11S'))  # ['aa]cc[,,]cc[mm0']
print(re.findall(r'\[(.*?)\]', 'www[aa]cc[,,]cc[mm0]11S'))  # 非贪婪,得到正确的

# re.escape 对字符串中所有可能被解释为正则运算符的字符,进行转义
print(re.escape('www.pp.com'))  # www\.pp\.com

# 匹配对象和 组
# group,start,end,span
# group 获取给定子模式(组)的匹配项
# start 返回给定组的匹配项的开始位置
# end 返回给定组的匹配项的开始位置
# span  返回一个组的开始和结束位置
m = re.match(r'www\.(.*)\..{3}', 'www.python.org')
print(m.group(1))  # python
print(m.start(1))  # 4
print(m.end(1))  # 10
print(m.span(1))  # (4,10)
m = re.match(r'www\.(.*)\..{3}', 'awww.python.org')  # 不能匹配,match是在字符串开始处查找

# re.sub 使用给定的替换内容将匹配模式的子字符串替换掉
print(re.sub('{name}', 'abc', 'hello {name}...'))  # hello abc...
# 作为替换的组号和函数
# re.sub 强大功能,在替换内容中以'\\n'形式出现的任何转义序列都会被模式中与组n匹配的字符串替换掉
# 例如要把'*something*' 用 '<em>something</em>' 替换掉
pat = r'\*([^\*]+)\*'  # []字符集,^反转除了*以外的字符
print(re.sub(pat, r'<em>\1</em>', 'Hello,*world*!'))  # Hello,<em>world</em>!
# re.sub高级,模板,见regular_test.py

# 给正则表达式加注释
# 在re 函数中使用VERBOSE 标志
pat = re.compile(r'''
\*  #comment1
(   #start group
[^\*]+  #get group
)   #end group
\*  #end
''', re.VERBOSE)


regular_test.py

#运行 python regular_test.py magnux.txt template.txt
import fileinput,re
pat=re.compile(r'\[(.+?)\]')    #非贪婪
scope={}
def replace(a):
code=a.group(1)
try:
return str(eval(code,scope))
except SyntaxError:
exec(code,scope)
return ''

lines=[]
for line in fileinput.input():
lines.append(line)

text=''.join(lines)
print(text)
print(pat.sub(replace,text))    #因为magnus.txt中是赋值,所以replace没有返回str 而是exec,
#所以没有打印


magnus.txt

[name='tttttt']
[email  =  'aaaa.com']
[langue = 'python']


template.txt

[import time]
Dear [name],
the [langue] asdf asdf asdf
[email]
[time.asctime()]

[x=1]
[y=2]
sum of [x] and [y] is [x+y]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: