当前位置 : 主页 > 编程语言 > python >

Python从门到精通(一):基础-05-RE正则表达式

来源:互联网 收集:自由互联 发布时间:2022-06-28
Reg的内容比较多,本章只简单描述下如何使用。至于正则的写法可网上查一下。能用好正则在某些场合下会达到事半功倍的效果。比如web端一些框架在查询dom时就大量使用了正则技术。

Reg的内容比较多,本章只简单描述下如何使用。至于正则的写法可网上查一下。能用好正则在某些场合下会达到事半功倍的效果。比如web端一些框架在查询dom时就大量使用了正则技术。

一、查找模式

import re

pattern = 'this'
text = 'Does this text match the pattern?'

match = re.search(pattern, text)

s = match.start()
e = match.end()

print('Found "{}"\nin "{}"\nfrom {} to {} ("{}")'.format(
match.re.pattern, match.string, s, e, text[s:e]))

Found "this"
in "Does this text match the pattern?"
from 5 to 9 ("this")

二、编译模式

这种模式比较高效

import re

# Precompile the patterns
regexes = [
re.compile(p)
for p in ['this', 'that']
]
text = 'Does this text match the pattern?'

print('Text: {!r}\n'.format(text))

for regex in regexes:
print('Seeking "{}" ->'.format(regex.pattern), end=' ')#end是个格式化输出,默认是换行,这处不换行

if regex.search(text):
print('match!')
else:
print('no match')
# Text: 'Does this text match the pattern?'
#
# Seeking "this" -> match!
# Seeking "that" -> no match

三、简单示例

3.1、修改字符串

import re

bold = re.compile(r'\*{2}(.*?)\*{2}')
text = 'Make this **bold**. This **too**.'
print('Text:', text)
print('Bold:', bold.sub(r'<b>\1</b>', text))
# Bold: Make this <b>bold</b>. This <b>too</b>.

3.2、拆分字符串

import re

text = '''Paragraph one
on two lines.

Paragraph two.


Paragraph three.'''

for num, para in enumerate(re.findall(r'(.+?)\n{2,}',
text,
flags=re.DOTALL)
):
print(num, repr(para))
print()
# 0 'Paragraph one\non two lines.'
#
# 1 'Paragraph two.'


上一篇:莫烦PyTorch学习笔记(六)——批处理
下一篇:没有了
网友评论