正则表达式基本用法

  喜欢我的博客可以加关注,有问题可以提问我。

  首先,我们来看看基本的正则表达式有哪些:

  1.最常规的匹配(匹配所有的字符)

import re
content = 'Hello 123 4567 World_this is a Regex Demo'
print(len(content))
result = re.match('^Hello\s\d\d\d\s\d{4}\s\w{10}.*Demo$',content)
print(result)
print(result.group())
print(result.span())

  2.范匹配

import re
content = 'Hello 123 4567 World_this is a Regex Demo'
result = re.match('^Hello.*Demo$',content)
print(result)
print(result.group())
print(result.span())

结果:
<_sre.SRE_Match object; span=(0, 41), match='Hello 123 4567 World_this is a Regex Demo'>
Hello 123 4567 World_this is a Regex Demo
(0, 41)

  3.匹配目标

import re
content = 'Hello 1234567 World_this is a Regex Demo'
result=re.match('^Hello\s(\d+)\sWorld.*Demo$',content)
print(result)
print(result.group(1))
print(result.span())

结果:
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_this is a Regex Demo'>
1234567
(0, 40)

  4.贪婪匹配

import re
content = 'Hello 1234567 World_this is a Regex Demo'
result=re.match('^He.*(\d+).*Demo$',content)
print(result)
print(result.group(1))

结果:
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_this is a Regex Demo'>
7

  5.非贪婪匹配

import re
content = "Hello 1234567 World_this is a Regex Demo"
result=re.match('^He.*?(\d+).*Demo$',content)
print(result)
print(result.group(1))

结果:
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_this is a Regex Demo'>
1234567

  6.匹配模式

import re
content = 'Hello 1234567 World_this \nis a Regex Demo'
result=re.match('^He.*?(\d+).*Demo$',content,re.S)
print(result)
print(result.group(1))
print(content)

结果:
<_sre.SRE_Match object; span=(0, 41), match='Hello 1234567 World_this \nis a Regex Demo'>
1234567
Hello 1234567 World_this 
is a Regex Demo

  7.转义

import re
content = 'price is $5.00'
result=re.match('price is $5.00',content)
print(result)

结果:None

import re
content = 'price is $5.00'
result=re.match('price is \$5\.00',content)
print(result)

结果:<_sre.SRE_Match object; span=(0, 14), match='price is $5.00'>

  8.re.search

import re
content = 'Extra stings Hello 1234567 World_this is a Regex Demo Extra stings'
result=re.match('Hello.*?(\d+).*Demo',content)
print(result)

结果:None

import re
content = 'Extra stings Hello 1234567 World_this is a Regex Demo Extra stings'
result=re.search('Hello.*?(\d+).*Demo',content)
print(result)
print(result.group(1))

结果:
<_sre.SRE_Match object; span=(13, 53), match='Hello 1234567 World_this is a Regex Demo'>
1234567

 

posted @ 2018-09-12 08:53  大神笨蛋  阅读(200)  评论(0编辑  收藏  举报