python字符串和正则表达式(6)

吉吉:

OC](python字符串和正则表达式
)

字符串概述

  • 在Python中,字符串属于不可变序列类型,不能修改已定义的字符串,除了支持序列通用方法(包括切片操作)以外,还支持特有的字符串操作方法。
  • Python字符串驻留机制:对于短字符串,将其赋值给多个不同的对象时,内存中只有一个副本,多个对象共享该副本。长字符串不遵守驻留机制。
  • Python 3.x完全支持中文字符,默认使用UTF8编码格式,无论是一个数字、英文字母,还是一个汉字,都按一个字符对待和处理。
    UTF-8对全世界所有国家需要用到的字符进行了编码,以1个字节表示英语字符(兼容ASCII),以3个字节表示中文,还有些语言的符号使用2个字节(例如俄语和希腊语符号)或4个字节。

>>> s = ‘中国湖北武汉'
>>> len(s)  #字符串长度,或者包含的字符个数
6
>>> s = ‘中国湖北武汉ABCDE'  #中文与英文字符同样对待,都算一个字符
>>> len(s)
11
>>> 姓名 = '张三'#使用中文作为变量名
>>> print(姓名)  #输出变量的值
张三

字符串格式化

  • 我们经常会输出类似‘亲爱的xxx你好!你xx月的话费是xx,余额是xx’之类的字符串,其中xxx的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式。
    在Python中,格式化字符串的方法有3种:
  • 1、使用%符号进行格式
  • 2、使用format()方法进行字符串格式化
  • 3、使用格式化的字符串常量f-string方法

%方法

  • 格式字符
  • 使用这种方式进行字符串格式化时,要求被格式化的内容和格式字符之间必须一一对应。

>>> x = 1235
>>> so="%o" % x
>>> so
"2323"
>>> sh = "%x" % x
>>> sh
"4d3"
>>> se = "%e" % x
>>> se
"1.235000e+03"

>>> print("123456789\n%8.2f"%54.26)  #宽度与精度设置
123456789
   54.26

#多个值输出采用tuple形式,使用元组对字符串进行格式化,按位置进行对应

>>> print ("Hello ,%s and %s." % ("Mike", "Jack"))
Hello, Mike and Jack.
  • 也可以利用格式字符进行字符类型的转换

    “%s”%65
    “65”

    “%d”%“555”
    TypeError: %d format: a number is required, not str

    ‘%s’%[1, 2, 3]
    ‘[1, 2, 3]’

    str((1,2,3))
    ‘(1, 2, 3)’

    str([1,2,3])
    ‘[1, 2, 3]’

format方法

  • 使用format方法进行格式化是python 3推荐的方法。该方法非常灵活,不仅可以使用位置进行格式化,还支持使用关键参数进行格式化,可调换顺序,支持序列解包格式化字符串,为程序员提供了非常大的方便。
  • 与上面讲到的 %s类似,不同的之处是将%s换成{ }大括号,可以通过{n}方式来指定接收参数的位置,将调用时传入的参数按照位置进行传入。相比%s可以减少参数的个数,实现了参数的复用。

 >>> print(‘{} {}’.format(‘hello’,‘world’)) # 不带编号,必须一一对应 
 hello world 
 >>> print('{0} {1}'.format('hello','world')) # 带数字编号 
 hello world 
 >>> print('{0} {1} {0}'.format('hello','world')) # 打乱顺序
 hello world hello 
 >>> print('{1} {1} {0}'.format('hello','world')) 
 world world hello 
 >>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字
 world hello world
  • 取位数:

>>> '{:10}'.format('hello') # 取10位默认左对齐
 'hello ' 
>>> '{0} is {1:.2f}'.format(1.123,1.123) # 取2位小数 
'1.123 is 1.12' 
>>>' {0:10.2} is {0:10.2f}'.format(1.123) 
# 取10位,第一个数保留2位有效位,第二个数保留2位小数,数字默认右对齐
'   1.1 is   1.12‘
  • 进制转换:

>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
 'int: 42; hex: 2a; oct: 52; bin: 101010‘
# 在前面加“#”,则带进制前缀 
>>>print("The number {0} in hex is: {0:#x}, the number {1} in oct is {1:#o}".format(5555,55)) 
The number 5555 in hex is: 0x15b3, the number 55 in oct is 0o67

左中右对齐及位数补全:< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐


>>> '{:<30}'.format('left aligned') # 左对齐
 'left aligned' 
>>> '{:>30}'.format('right aligned') # 右对齐 
'   right aligned' 
>>> '{:^30}'.format('centered') # 中间对齐
 '   centered' 
>>> '{:*^30}'.format('centered') # 使用“*”填充 '***********centered***********' 
>>>'{:0=30}'.format(11) # 还有“=”只能应用于数字,这种方法可用“>”代替
 '000000000000000000000000000011'
  • ‘%’ - 百分数。将数值乘以100然后以fixed-point(‘f’)格式打印,值后面会有一个百分号。

>>> print('{:%}'.format(20)) 20 
2000.000000%

>>> points = 19 
>>> total = 22 
>>> 'Correct answers: {:.2%}'.format(points/total)
 'Correct answers: 86.36%'
  • 使用元组,实现多个变量一次输出。

>>>position = (5,8,13)
>>>print("X:{0[0]};Y:{0[1]};Z:{0[2]}".format(position))
X:5;Y:8;Z:13


weather = [("Monday","rain"),("Tuesday","sunny"),("Wednesday", "sunny"),("Thursday","rain"),("Friday","Cloudy")]
formatter = “Weather of ‘{0[0]}’ is ‘{0[1]}’”.format #把format方法当作函数
for item in map(formatter,weather): #将formatter映射到weather的每一个元素上
print(item)
for item in weather:
print(formatter(item))
Weather of 'Monday' is 'rain'
Weather of 'Tuesday' is 'sunny'
Weather of 'Wednesday' is 'sunny'
Weather of 'Thursday' is 'rain'
Weather of 'Friday' is 'Cloudy'

-通过{str}方式来指定名字,调用时使用str=‘xxx’,确定参数传入。


>>>print("my name is {name}, my age is {age}, and my QQ is {qq}".format(name = "Zo Qng",age = 41,qq = "1232123123"))
my name is Zo Qng, my age is 41, and my QQ is 1232123123
  • 使用元组,实现多个变量一次输出。

>>>position = (5,8,13)
>>>print("X:{0[0]};Y:{0[1]};Z:{0[2]}".format(position))
X:5;Y:8;Z:13
  • f-string方法
  • 从Python 3.6.x开始支持一种新的字符串格式化方式,官方叫做Formatted String Literals,其含义与字符串对象的format()方法类似,但形式更加简洁。
  • f-string是一个文本字符串,前缀为f。

>>> name = 'Zou'
>>> age = 41
>>> f'My name is {name}, and I am {age} years old.'
'My name is Zou, and I am 41 years old.'
  • 输出宽度及小数位数可以取决于某变量,变量还是用{}括起来,例如让%10.2f里的10用变量表示,即总宽度可灵活变化

>>> width = 10
>>> precision = 4
>>> value = 11/3
>>> f‘result:{value:{width}.{precision}}’  #总宽度和精度设置
'result: 3.667'

>>> a=10
>>> b=4
>>> c=2
>>> x=123.567
>>> f"{x:{a}.{b}}"
'123.6'
>>> f“{x:{a}.{c}f}”   #小数位数
'123.57'
  • f -string提供了一种方法,可以在字符串文字中嵌入表达式,使用最小的语法。括号内的表达式,在运行时被替换为它们的值。

>>> a=5
>>> f"{a*3}"
'15'
>>> a='5'
>>> f"{a*3}"
'555'

字符串特殊方法

  • 1、字符串常量:
    Python标准库string中定义数字字符、标点符号、英文字母、大写字母、小写字母等常量。

>>> import string
>>> string.digits
'0123456789'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.ascii_letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  • 随机密码生成原理

>>> import string
>>> x = string.digits + string.ascii_letters + string.punctuation
>>> x
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> import random
>>> ‘’.join([random.choice(x) for i in range(8)])#字符串的join方法、列表推导式、random.choice方法
'H\\{.#=)g'
>>> ''.join([random.choice(x) for i in range(8)])
'(CrZ[44M'
>>> ''.join([random.choice(x) for i in range(8)])
'o_?[M>iF'
>>> ''.join([random.choice(x) for i in range(8)])
'n<[I)5V@'
  • maketrans()方法和translate()方法:
    字符串对象的maketrans()方法用来生成字符映射表,而translate()方法用来根据映射表中定义的对应关系转换字符串并替换其中的字符,使用这两个方法的组合可以同时处理多个不同的字符,replace()方法则无法满足要求。

#创建映射表,将字符"abcdef123"一一对应地转换为"uvwxyz@#$"
>>> table = ''.maketrans('abcdef123', 'uvwxyz@#$')
>>> s = "Python is a greate programming language. I like it!"
#按映射表进行替换
>>> s.translate(table)
'Python is u gryuty progrumming lunguugy. I liky it!'
  • 凯撒加密
    凯撒加密法,是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。

>>> import string
>>> def kaisa(s, k):
	lower = string.ascii_lowercase  #小写字母
	upper = string.ascii_uppercase  #大写字母
	before = string.ascii_letters   #所有字母	after = lower[k:] + lower[:k] + upper[k:] + upper[:k]
	table = ''.maketrans(before, after) #创建映射表
	return s.translate(table)

>>> s = "Python is a greate programming language. I like it!"
>>> kaisa(s, 3)
'Sbwkrq lv d juhdwh surjudpplqj odqjxdjh. L olnh lw!'
  • s.startswith(t)、s.endswith(t)方法:
    判断字符串是否以指定字符串开始或结束

>>> s = 'Beautiful is better than ugly.'
>>> s.startswith('Be') #检测整个字符串
True
>>> s.startswith('Be', 5) #指定检测范围起始位置
False
>>> s.startswith('Be', 0, 5) #指定检测范围起始和结束位置
True
>>> import os
>>> [filename for filename in os.listdir(r'c:\\') if filename.endswith(('.bmp','.jpg','.gif'))]
  • 、isalnum()、isalpha()、isdigit()、isdecimal()、isnumeric()、isspace()、isupper()、islower():
    用来测试字符串是否为数字或字母、是否为字母、是否为数字字符、是否为空白字符、是否为大写字母以及是否为小写字母。

>>> '1234abcd'.isalnum()
True
>>> '1234abcd'.isalpha() #全部为英文字母时返回True
False
>>> '1234abcd'.isdigit() #全部为数字时返回True
False
>>> 'abcd'.isalpha()
True
>>> '1234.0'.isdigit()
False
  • 内置函数eval():
    把任意字符串转化为python表达式并求值。

>>> eval("3+4")
7
>>> a = 3
>>> b = 5
>>> eval('a+b')
8
>>> import math
>>> eval('math.sqrt(3)')
1.7320508075688772
>>> eval('aa')
NameError: name 'aa' is not defined
  • eval()函数是非常危险的

    a = input(“Please input:”)
    Please input:import(‘os’).startfile(r’C:\Windows\notepad.exe’)

    eval(a)
    eval(“import(‘os’).system(‘md testtest’)”)

  • 检查并判断密码字符串的安全强度。

im


port string

def check(pwd):
#检查pwd是否为字符串且密码必须至少包含6个字符
if not isinstance(pwd, str) or len(pwd)<6:  
return 'not suitable for password'
#密码强度等级与包含字符种类的对应关系,用字典存储
d = {1:'weak', 2:'below middle', 3:'above middle', 4:'strong'}
#分别用来标记pwd是否含有数字、小写字母、大写字母和指定的标点符号
r = [False] * 4

正则表达式

  • 正则表达式是字符串处理的有力工具和技术。(英语:Regular Expression,在代码中常简写为regex、regexp或RE)
  • 正则表达式使用某种预定义的模式去匹配一类具有共同特征的字符串,主要用于处理字符串,可以快速、准确地完成复杂的查找、替换等处理要求。在文本编辑、网页爬虫之类的场合有重要的应用。
  • Python中,re模块提供了正则表达式操作所需要的功能。

正则表达式语法

  • 可以把一对圆括号内的内容当做一个字符,外面可以加我们之前讲过的所有元字符来控制匹配。

  • 使用()表示一个子模式,即()内的内容作为一个整体出现,例如’(red)+’可以匹配’redred’、’redredred‘等多个重复’red’的情况。

  • 最简单的正则表达式是普通字符串,可以匹配自身

  • ‘[pjc]ython’可以匹配’python’、‘jython’、‘cython’

  • '[a-zA-Z0-9]'可以匹配一个任意大小写字母或数字

  • '[^abc]‘可以匹配任意一个除’a’、‘b’、'c’之外的字符

  • 'python|perl’或’p(ython|erl)‘都可以匹配’python’或’perl’

  • 子模式后面加上问号表示可选。r’(http://)?(www.)?python.org’只能匹配’http://www.python.org’、‘http://python.org’、‘www.python.org’和’python.org

  • '^http’只能匹配所有以’http’开头的字符串

  • (pattern)*:允许模式重复0次或多次

  • (pattern)+:允许模式重复1次或多次

  • (pattern){m,n}:允许模式重复m~n次

  • ‘(a|b)*c’:匹配多个(包含0个)a或b,后面紧跟一个字母c。

  • ‘ab{1,}’:等价于’ab+’,匹配以字母a开头后面带1个至多个字母b的字符串。

  • '1{1}([a-zA-Z0-9.]){4,19}$’:匹配长度为5-20的字符串,必须以字母开头、可带数字、“”、“.”的字串。

  • ‘^(\w){6,20}$’:匹配长度为6-20的字符串,可以包含字母、数字、下划线。

  • ‘^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$’:检查给定字符串是否为合法IP地址。

  • ‘^(13[4-9]\d{8})|(15[01289]\d{8})$’:检查给定字符串是否为移动手机号码。

  • 2+$’:检查给定字符串是否只包含英文字母大小写。

  • ‘^\w+@(\w+.)+\w+$’:检查给定字符串是否为合法电子邮件地址。

  • ‘^(-)?\d+(.\d{1,2})?$’:检查给定字符串是否为最多带有2位小数的正数或负数。

  • ‘[\u4e00-\u9fa5]’:匹配给定字符串中所有汉字。

  • ‘^\d{18}|\d{15}$’:检查给定字符串是否为合法身份证格式。

  • ‘\d{4}-\d{1,2}-\d{1,2}’:匹配指定格式的日期,例如2016-1-31。

  • ‘(.)\1+’:匹配任意字符的一次或多次重复出现。

re模块主要方法


>>> import re#导入re模块
>>> text = 'alpha. beta....gamma delta'  #测试用的字符串
>>> re.split(‘[\. ]+’, text)   #使用匹配的字符作为分隔符进行分隔
['alpha', 'beta', 'gamma', 'delta']
>>> re.split('[\. ]+', text, maxsplit=2) #最多分隔2次
['alpha', 'beta', 'gamma delta']
>>> re.split('[\. ]+', text, maxsplit=1) #最多分隔1次
['alpha', 'beta....gamma delta']
>>> pat = '[a-zA-Z]+'
>>> re.findall(pat, text)#查找所有单词
['alpha', 'beta', 'gamma', 'delta']

>>> re.sub(‘a’, ‘dfg’, ‘aaa abc abde’) #返回替换后的新字符串
'dfgdfgdfg dfgbc dfgbde'
>>> re.subn('a', 'dfg', 'aaa abc abde') #返回新字符串和替换次数
('dfgdfgdfg dfgbc dfgbde', 5)
>>> s = 'a s d'
>>> re.sub('a|s|d', 'good', s) #字符串替换
'good good good'
>>> s = "It's a very good good idea"
>>> re.sub(r'(\b\w+) \1', r'\1', s)#处理连续的重复单词
#如果你没有使用 raw 字符串时,那么 Python 将会把 “\b” 转换成一个回退符,re 将无法象你希望的那样匹配它了。
"It's a very good idea"

>>> re.escape('http://www.python.org')  #字符串转义
'http\\:\\/\\/www\\.python\\.org'
>>> example = 'Beautiful is better than ugly.'
>>> re.findall('\\bb.+?\\b', example)   #以字母b开头的完整单词
#此处问号?表示非贪心模式
['better']
>>> re.findall('\\bb.+\\b', example)   #贪心模式的匹配结果
['better than ugly']
>>> re.findall('\\bb\w*\\b', example)
['better']
>>> re.findall('\\Bh.+?\\b', example)#不以h开头且含有h字母的单词剩余部分
['han']
>>> re.findall(‘\\b\w.+?\\b’, example) #所有单词 
#\b表示单词与非单词的边界(单词包括字母、数字、下划线)
['Beautiful', 'is', 'better', 'than', 'ugly']
>>> re.findall('\d+\.\d+\.\d+', 'Python 2.7.13')
   #查找并返回x.x.x形式的数字
['2.7.13']
>>> re.findall('\d+\.\d+\.\d+', 'Python 2.7.13,Python 3.6.0')
['2.7.13', '3.6.0']
>>> text = "He was carefully disguised but captured quickly by police."
>>> re.findall(r"\w+ly", text)   #查找所有以字母组合ly结尾的单词
['carefully', 'quickly']

使用正则表达式对象

  • 首先使用re模块的compile()方法将正则表达式编译生成正则表达式对象,然后再使用正则表达式对象提供的方法进行字符串处理。
  • 使用编译后的正则表达式对象可以提高字符串处理速度。

re.compile(pattern, flags=0)
pattern 指定编译时的表达式字符串;
flags 编译标志位,用来修改正则表达式的匹配方式。flags 标志位参数
re.I(re.IGNORECASE) :使匹配对大小写不敏感
re.L(re.LOCAL) :做本地化识别(locale-aware)匹配
re.M(re.MULTILINE) :多行匹配,影响 ^ 和 $
re.S(re.DOTALL) :使 . 匹配包括换行在内的所有字符
re.U(re.UNICODE):根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
re.X(re.VERBOSE):该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。

  • findall()

>>> import re
>>> example = 'ShanDong Institute of Business and Technology'
>>> pattern = re.compile(r'\bB\w+\b')#查找以B开头的单词
>>> pattern.findall(example)  #使用正则表达式对象的findall()方法
['Business']
>>> pattern = re.compile(r'\w+g\b')   #查找以字母g结尾的单词
>>> pattern.findall(example)
['ShanDong']
>>> pattern = re.compile(r'\b[a-zA-Z]{3}\b')#查找3个字母长的单词
>>> pattern.findall(example)
['and']
>>> pattern = re.compile(r'\b\w*a\w*\b') #查找所有含有字母a的单词
>>> pattern.findall(example)
['ShanDong', 'and']
  • sub()、subn()
    Sub(replacement,string[,count =0 ])
    1)返回的字符串是在字符串中用replacement来替换。如果模式没有被发现,字符将没有被改变的返回。
    2)可选参数count是模式匹配后替换的最大次数;count必须是非负整数。缺省值是0表示替换所有的匹配。

>>> example = '''Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.'''
>>> pattern = re.compile(r'\bb\w*\b', re.I)  #匹配以b或B开头的单词
#re.I(re.IGNORECASE) :使匹配对大小写不敏感

>>> print(pattern.sub('*', example))#将符合条件的单词替换为*
* is * than ugly.
Explicit is * than implicit.
Simple is * than complex.
Complex is * than complicated.
Flat is * than nested.
Sparse is * than dense.
Readability counts.
>>> print(pattern.sub('*', example, 1))  #只替换1次
* is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
>>> pattern = re.compile(r'\bb\w*\b')#匹配以字母b开头的单词
>>> print(pattern.sub('*', example, 1)) #将符合条件的单词替换为*
   #只替换1次
Beautiful is * than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
  • 正则表达式对象的split(string[, maxsplit = 0])方法用来实现字符串分隔。

>>> example = r'one,two,three.four/five\six?seven[eight]nine|ten'
>>> pattern = re.compile(r'[,./\\?[\]\|]') #指定多个可能的分隔符
>>> pattern.split(example)
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
>>> example = r'one1two2three3four4five5six6seven7eight8nine9ten'
>>> pattern = re.compile(r'\d+')  #使用数字作为分隔符
>>> pattern.split(example)
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
>>> example = r'one twothree  four,five.six.seven,eight,nine9ten'
>>> pattern = re.compile(r'[\s,.\d]+')   #允许分隔符重复
>>> pattern.split(example)
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']

子模式与match对象

  • 使用()表示一个子模式,即()内的内容作为一个整体出现,例如’(red)+’可以匹配’redred’、’redredred‘等多个重复’red’的情况。

>>> telNumber = '''Suppose my Phone No. is 0535-1234567,
yours is 010-12345678, his is 025-87654321.'''
>>> pattern = re.compile(r'(\d{3,4})-(\d{7,8})')
>>> pattern.findall(telNumber)
[('0535', '1234567'), ('010', '12345678'), ('025', '87654321')]
  • 正则表达式对象的match方法和search方法匹配成功后返回match对象。
  • match对象的主要方法有:

group():返回匹配的一个或多个子模式内容
groups():返回一个包含匹配的所有子模式内容的元组
groupdict():返回包含匹配的所有命名子模式内容的字典
start():返回指定子模式内容的起始位置
end():返回指定子模式内容的结束位置的前一个位置
span():返回一个包含指定子模式内容起始位置和结束位置前一个位置的元组。

  • match对象的group()、groups()与groupdict()以及其他方法的用法

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)   #返回整个模式内容
'Isaac Newton'
>>> m.group(1)   #返回第1个子模式内容
'Isaac'
>>> m.group(2)   #返回第2个子模式内容.
'Newton'
>>> m.group(1, 2)#返回指定的多个子模式内容
('Isaac', 'Newton')
>>> pattern = re.compile(r'(?<=\w\s)never')#查找位于句子末尾的单词
>>> matchResult = pattern.search(exampleString)
>>> matchResult.span()
(156, 161)
>>> pattern = re.compile(r'(?:is\s)better(\sthan)')#查找前面是is的better than组合
>>> matchResult = pattern.search(exampleString)
>>> matchResult.span()
(141, 155)
>>> matchResult.group(0)   #组0表示整个模式
'is better than'
>>> matchResult.group(1)
' than'
  • 子模式扩展语法:

  • (?P):为子模式命名

  • (?iLmsux):设置匹配标志,可以是几个字母的组合,每个字母含义与编译标志相同

  • (?:…):匹配但不捕获该匹配的子表达式

  • (?P=groupname):表示在此之前的命名为groupname的子模式

  • (?#…):表示注释

  • (?=…):用于正则表达式之后,表示如果=后的内容在字符串中出现则匹配,但不返回=之后的内容

  • (?!..):用于正则表达式之后,表示如果!后的内容在字符串中不出现则匹配,但不返回!之后的内容

  • (?<=…):用于正则表达式之前,与(?=…)含义相同

  • (?<!..):用于正则表达式之前,与(?!..)含义相同

  • ‘^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[,._]).{8,}$’:检查给定字符串是否为强密码,必须同时包含英语字母大写字母、英文小写字母、数字或特殊符号(如英文逗号、英文句号、下划线),并且长度必须至少8位。

  • “(?!.*[’”/;=%?]).+":如果给定字符串中包含’、”、/、;、=、%、?则匹配失败。

  • ‘(.)\1+’:匹配任意字符的一次或多次重复出现。

  • ‘((?P\b\w+\b)\s+(?P=f))’:匹配连续出现两次的单词。

  • ‘((?P.)(?P=f)(?P .)(?P=g))’:匹配AABB形式的成语或字母组合。


>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.group('first_name')  #使用命名的子模式
'Malcolm'
>>> m.group('last_name')
'Reynolds'
>>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
>>> m.groups()  #返回所有匹配的子模式(不包括第0个)
('24', '1632')
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.groupdict() #以字典形式返回匹配的结果
{'first_name': 'Malcolm', 'last_name': 'Reynolds'}
>>> exampleString = '''There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.'''
>>> pattern = re.compile(r'(?<=\w\s)never(?=\s\w)')  #查找不在句子开头和结尾的never
>>> matchResult = pattern.search(exampleString)
>>> matchResult.span()
(172, 177)
>>> pattern = re.compile(r'\b(?i)n\w+\b')  #查找以n或N字母开头的所有单词
>>> index = 0
>>> while True:
	matchResult = pattern.search(exampleString, index)
	if not matchResult:
		break
	print(matchResult.group(0), ':', matchResult.span(0))
	index = matchResult.end(0)
not : (92, 95)
Now : (137, 140)
never : (156, 161)
never : (172, 177)
now : (205, 208)
>>> pattern = re.compile(r'(?<!not\s)be\b')  #查找前面没有单词not的单词be
>>> index = 0
>>> while True:
	matchResult = pattern.search(exampleString, index)
	if not matchResult:
		break
	print(matchResult.group(0), ':', matchResult.span(0))
	index = matchResult.end(0)
be : (13, 15)
>>> exampleString[13:20]#验证一下结果是否正确
'be one-'
>>> pattern = re.compile(r'(\b\w*(?P<f>\w+)(?P=f)\w*\b)')  #有连续相同字母的单词
>>> index = 0
>>> while True:
	matchResult = pattern.search(exampleString, index)
	if not matchResult:
		break
	print(matchResult.group(0), ':', matchResult.group(2))
	index = matchResult.end(0) + 1
unless : s
better : t
better : t
>>> s = 'aabc abcd abbcd abccd abcdd'
>>> pattern.findall(s)
[('aabc', 'a'), ('abbcd', 'b'), ('abccd', 'c'), ('abcdd', 'd')]

  1. a-zA-Z ↩︎

  2. a-zA-Z ↩︎

发布了44 篇原创文章 · 获赞 82 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/weixin_41503009/article/details/85654411