python解析之正则表达式,由浅入深带你轻松学会正则表达式(04 边界限定以及优先级控制)

正则匹配中如果匹配中想要查找以xxx开头或者结尾要用到边界限定,如下:

^  :以指定内容开头

$ :以指定内容结尾

示例代码:

import re

# ^:以指定内容开头
f = re.findall('^hello', 'hellosjdhelloalskdhello')
print(f)


# $:以指定内容结尾
f = re.findall('hello$', 'hellosjdhelloalskdhello')

print(f)

代码运行结果:

匹配中如果要用到优先级的问题可用以下的方法;

| :表示或,它拥有最低的优先级

() :表示一个整体,可以明确的指定结合性/优先级

示例代码:

import re

f = re.findall('a(hello|world)c', 'sahdjsahellocaworldcjsdhs')

print(f)

运行结果:

猜你喜欢

转载自blog.csdn.net/z_xiaochuan/article/details/81585347
今日推荐