【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'
相关推荐
互联网中的一颗神经元4 天前
小白python入门 - 23. Python 正则表达式的应用
python·正则表达式
2501_936415694 天前
API-正则表达式&时间&包装类
正则表达式
鹤卿1238 天前
谓词与正则表达式(OC)
ios·正则表达式·objective-c·xcode
饼干哥哥11 天前
10.5% 深层转化、90%+ 新用户,ChatGPT Ads 值得吗?
算法·正则表达式·编程语言
饼干哥哥12 天前
Seedance TK视频「真人感」问题的 9 个解法
正则表达式·代码规范·设计
逝水无殇13 天前
C# 正则表达式详解
开发语言·后端·正则表达式·c#
木木子2217 天前
# 密码强度检测深度解析:正则表达式实时分析、多维度评分算法与可视化反馈
mysql·算法·华为·正则表达式·harmonyos
饼干哥哥18 天前
用Claude Code跑通跨境电商的5大场景,顶10个人的团队
人工智能·设计模式·正则表达式
饼干哥哥19 天前
单篇100万阅读文章,如何用AI 做好内容创作?
人工智能·正则表达式·代码规范
无足鸟ICT20 天前
【RHCA+】扩展正则表达式
linux·正则表达式