【Python入门第二十九天】Python RegEx

RegEx 或正则表达式是形成搜索模式的字符序列。

RegEx 可用于检查字符串是否包含指定的搜索模式。

RegEx 模块

Python 提供名为 re 的内置包,可用于处理正则表达式。

导入 re 模块:

import re

Python 中的 RegEx

导入 re 模块后,就可以开始使用正则表达式了:

实例

检索字符串以查看它是否以 “China” 开头并以 “country” 结尾:

import re

txt = "China is a great country"
x = re.search("^China.*country$", txt)

运行实例

import re

txt = "China is a great country"
x = re.search("^China.*country$", txt)

if (x):
  print("YES! We have a match!")
else:
  print("No match")

RegEx 函数

re 模块提供了一组函数,允许我们检索字符串以进行匹配:

元字符

元字符是具有特殊含义的字符

字符:[]
描述:一组字符
示例:“[a-m]”

import re

str = "The rain in Spain"

#Find all lower case characters alphabetically between "a" and "m":

x = re.findall("[a-m]", str)
print(x)

运行示例

字符:
描述:示意特殊序列(也可用于转义特殊字符)
示例:“\d”

import re

str = "That will be 59 dollars"

#Find all digit characters:

x = re.findall("\d", str)
print(x)

运行示例

字符:.
描述:任何字符(换行符除外)
示例: “he…o”

import re

str = "hello world"

#Search for a sequence that starts with "he", followed by two (any) characters, and an "o":

x = re.findall("he..o", str)
print(x)

运行示例

字符:^
描述:起始于
示例: “^hello”

import re

str = "hello world"

#Check if the string starts with 'hello':

x = re.findall("^hello", str)
if (x):
  print("Yes, the string starts with 'hello'")
else:
  print("No match")

运行示例

字符:$
描述:结束于
示例:“world$”

import re

str = "hello world"

#Check if the string ends with 'world':

x = re.findall("world$", str)
if (x):
  print("Yes, the string ends with 'world'")
else:
  print("No match")

运行示例

字符:*
描述:零次或多次出现
示例:“aix*”

import re

str = "The rain in Spain falls mainly in the plain!"

#Check if the string contains "ai" followed by 0 or more "x" characters:

x = re.findall("aix*", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

运行示例

字符:+
描述:一次或多次出现
示例: “aix+”

import re

str = "The rain in Spain falls mainly in the plain!"

#Check if the string contains "ai" followed by 1 or more "x" characters:

x = re.findall("aix+", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

运行示例

字符:{}
描述: 确切地指定的出现次数
示例:“al{2}”

import re

str = "The rain in Spain falls mainly in the plain!&
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值