正则表达式(re)
什么是正则表达式?
通配符
转义字符
字符集
选择和子模式(Alternatives and Subpatterns)
可选和重复子模式(optional and Repeated Subpatterns)
re模块中的一些函数:
compile(pattern[, flags])
search(pattern, string[, flag])
match(pattern, string[, flag])
split(pattern, string[, maxsplit=0])
>>> some_text = 'alpha, beta,,,,gamma
>>> re.split('[, ]+', some_text)
['alpha', 'beta', 'gamma', 'delta']
delta'
findall(pattern, string)
sub(pat, repl, string[, count=0])
>>> pat = '{name}'
>>> text = 'Dear {name}...'
>>> re.sub(pat, 'Mr. Gumby', text)
'Dear Mr. Gumby...'
escape(string)
>>> re.escape('www.python.org')
'www\\.python\\.org'
>>> re.escape('But where is the ambiguity?')
'But\\ where\\ is\\ the\\ ambiguity\\?'
flag
匹配对象和分组(Match Object and Groups)
分组号和替换函数:
>>> emphasis_pattern = r'\*([^\*]+)\*'
>>> re.sub(emphasis_pattern, r'<em>\1</em>', 'Hello, *world*!')
'Hello, <em>world</em>!'
贪心和非贪心模式(greedy and nongreedy pattern)
>>> emphasis_pattern = r'\*(.+)\*'
>>> re.sub(emphasis_pattern, r'<em>\1</em>', '*This* is *it*!')
'<em>This* is *it</em>!'
模式串匹配了从第一个一直到最后一个星号。如果不想这样,可以在后面加个问好(?),这样的话,就是使用非贪心的版本。所有的重复操作符后面加了问号的话,都会调用非贪心的版本。
>>> emphasis_pattern = r'\*\*(.+?)\*\*'
>>> re.sub(emphasis_pattern, r'<em>\1</em>', '**This** is **it**!')
'<em>This</em> is <em>it</em>!'
一个简单的模板系统:
#templates.py
import fileinput, re
#Matches fields enclosed in square brackets:
field_pat = re.compile(r'\[(.+?)\]')
#We'll collect variables in this:
scope = {}
#This is used in re.sub:
def replacement(match):
code = match.group(1)
try:
#If the field can be evaluated, return it:
return str(eval(code, scope))
except SyntaxError:
# Otherwise, execute the assignment in the same scope...
exec code in scope
# ... and return an empty string:
return ''
#Get all the text as a single string:
# (There are other ways of doing this; see Chapter 11)
lines = []
for line in fileinput.input():
lines.append(line)
text = ''.join(lines)
# Substitute all the occurrences of the field pattern:
print field_pat.sub(replacement, text)
这段代码完成的工作有
- 为匹配的域定义一个模式
- 定义一个字典,作为模板的scope
- 定义一个replacement函数,完成以下的事情
- 从match中抓获group1,然后把获取的值存入code中。
- 对code中间的字符串在scope域中进行求值计算,或者(symtaxError被抛出)
- 在scope域中执行获取的字符串。
- 从文件中读取所有的行,放在一个List中,然后合成一个大的字符串。
- 利用replace函数的返回值替换所有的匹配的值
[name= 'Magnus Lie Hetland' ]
[email= 'magnus@foo.bar']
[language = 'python']
[import time]
Dear [name],
I would like to learn how to program. I hear you use
the [language] language a lot -- is it something I
should consider?
And, by the way, is [email] your correct email address?
Fooville, [time.asctime()]
Oscar Frozzbozz
$python templates.py magnus.txt templates.txt
1046



被折叠的 条评论
为什么被折叠?



