【Leetcode】正则表达式

正则表达式:检查字符串是否与指定模式匹配

指定模式:re.compile(r'xxxxxxx')

|---------|--------|-----|------|-----|------|
| 符号 | 规则 | 规则释义 ||||
| ^ | 指定开头 | ^S 匹配以S开头的字符串 ||||
| | 指定结尾 | a 匹配以a结尾的字符串 ||||
| ^ | 严格匹配 | \^Sa 只能匹配Sa ||||
| [] | 字符簇 | [a-z0-9] 匹配小写字符或数字 ||||
| [^ ] | 排除 | [^A-Z] 排除对大写字符的匹配 ||||
| . | 任意字符 | ^.a 匹配任意长度为2且以a结尾的字符串 |||| | {m,n} | 限制出现次数 | a{3,} 匹配任意以3个及3个以上a结尾的字符串 ||||
| ? | {0,1} | * | {0,} | + | {1,} |
| .* | 贪婪匹配:匹配尽可能多的字符 || .*? | 懒惰匹配:匹配尽可能少的字符 ||
| \d | 匹配数字 | \w | 匹配字符 | \s | 匹配空格 |

处理函数

  1. re.match(pattern, string, flags):从字符串的指定位置(默认起始)尝试匹配;

匹配成功返回匹配对象(可通过.span()获得坐标信息),匹配失败返回None

python 复制代码
import re
re.match('www', 'www.runoob.com').span()         # 在起始位置匹配
return (0,3)
re.match('com', 'www.runoob.com')                # 不在起始位置匹配
return None


pattern = re.compile(r'\d+')
m = pattern.match('one12twothree34four')            # 默认起始位置匹配
m = pattern.match('one12twothree34four', 2, 10)     # 指定位置匹配

2.re.search(pattern, string, flags):在完整字符串中尝试匹配;

匹配成功返回第一个成功匹配的对象(可通过.span()获得坐标信息),匹配失败返回None

python 复制代码
import re
re.match('www', 'www.runoob.com').span() 
return (0,3)
re.match('com', 'www.runoob.com').span()  
return (11,14)

3.re.sub(pattern, restr, string, count, flags):替换字符串中的匹配项

restr 替换字符串 count 替换次数,默认全部替换

python 复制代码
import re
 
phone = "2004-959-559 # 这是一个国外电话号码"
 
# 删除非数字(-)的字符串 
num = re.sub(r'\D', "", phone)
return 2004959559

4.findall:在字符串中找到正则表达式所匹配的所有子串

python 复制代码
import re
 
pattern = re.compile(r'\d+')                                    # 确定规则:查找数字
result1 = pattern.findall('runoob 123 google 456')              # 全局匹配
result2 = pattern.findall('run88oob123google456', 0, 10)        # 指定范围匹配


result = re.findall(r'(\w+)=(\d+)', 'set width=20 and height=10') 
return [('width', '20'), ('height', '10')]

match和search区别:匹配范围

findall和match/search区别:匹配次数

468 验证IP地址

给定一个字符串 queryIP。如果是有效的 IPv4 地址,返回 "IPv4" ;如果是有效的 IPv6 地址,返回 "IPv6" ;如果不是上述类型的 IP 地址,返回 "Neither"有效的IPv4地址"x1.x2.x3.x4" 形式的IP地址。 其中 0 <= xi <= 255xi 不能包含 前导零。有效的IPv6地址 是一个格式为"x1:x2:x3:x4:x5:x6:x7:x8" 的IP地址,其中:1 <= xi.length <= 4xi 是一个 十六进制字符串 ,可以包含数字、小写英文字母( 'a''f' )和大写英文字母( 'A''F' );在 xi 中允许前导零。

python 复制代码
import re

def check_ip4(IP):
    for strr in IP:
        if len(strr)>1 and strr[0]=='0': return False
        if int(strr)>255: return False

    return True

class Solution(object):
    def validIPAddress(self, queryIP):
        """
        :type queryIP: str
        :rtype: str
        """
        ipv4 = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
        ip4 = ipv4.findall(queryIP)

        ipv6 = re.compile(r'[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}')
        ip6 = ipv6.findall(queryIP)

        if ip6 and ip6[0] == queryIP: return 'IPv6'
        if ip4 and ip4[0] == queryIP and check_ip4(ip4[0].split('.')): return 'IPv4'
        return 'Neither'
相关推荐
m0_64880493_江哥20 小时前
用正则方法从中英文本提取英文的python示例
python·mysql·正则表达式
九皇叔叔1 天前
Linux Shell 正则表达式:从入门到实战,玩转文本匹配与处理
linux·mysql·正则表达式
一百天成为python专家2 天前
python爬虫入门(小白五分钟从入门到精通)
开发语言·爬虫·python·opencv·yolo·计算机视觉·正则表达式
蓝桉~MLGT3 天前
Python学习历程——字符串相关操作及正则表达式
python·学习·正则表达式
一晌小贪欢3 天前
Python爬虫第5课:正则表达式与数据清洗技术
爬虫·python·正则表达式·网络爬虫·python爬虫·python3·网页爬虫
MANONGMN4 天前
Linux 通配符与正则表达式(含实战案例+避坑指南)
linux·运维·正则表达式
带土14 天前
18 .shell编程-正则表达式
linux·正则表达式
2025年一定要上岸4 天前
【日常学习】10-15 学习re
学习·算法·正则表达式
Penguin_zlh8 天前
基础 - 正则表达式
正则表达式
超级大只老咪8 天前
正则表达式
正则表达式