Python学习笔模式匹配与正则表达式之插入字符和美元字符

随笔记录方便自己和同路人查阅。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  可以在正则表达式的开始处使用插入符号(^),表明匹配必须发生在被查找文本开始处。类似地,可以在正则表达式

末尾加上美元符号($),表示该字符串必须以这个正则表达式的模式结束。可以同时使用(^)和($),表明整个字符串必须匹

配该模式,也就是说,只匹配该字符串的某个子集是不够的。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  1、^匹配开始位置字符串,示例代码:

#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
import re
beginsWithHello = re.compile(r'^Hello')
mo = beginsWithHello.search('Hello world!')
print(mo.group())

  运行结果:

  错误示例代码:

import re
beginsWithHello = re.compile(r'^Hello')
if beginsWithHello.search('He said hello.') == None:
     print('True')

  运行结果:

  2、$匹配结束位置字符串,示例代码:

#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
import re
beginsWithHello = re.compile(r'world!$')#使用$美元符检查结束位置是否符合该内容
mo = beginsWithHello.search('Hello world!')
print(mo.group())

  运行结果:

  错误示例代码:

#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
import re
beginsWithHello = re.compile(r'Hello$')#使用$美元符检查结束位置是否符合该内容
if beginsWithHello.search('Hello world!') ==None:
    print('True')

  运行结果:

原文地址:https://www.cnblogs.com/lirongyang/p/9575436.html