import re
# 示例1: 匹配以 "hello" 开头的字符串
pattern = r'^hello'
text = 'hello world'
match = re.match(pattern, text)
if match:
print("匹配成功:", match.group())
else:
print("匹配失败")
# 示例2: 查找所有数字
pattern = r'\d+'
text = '123 apples and 456 oranges'
matches = re.findall(pattern, text)
print("找到的数字:", matches)
# 示例3: 替换指定模式
pattern = r'world'
replacement = 'everyone'
text = 'hello world'
new_text = re.sub(pattern, replacement, text)
print("替换后的文本:", new_text)
# 示例4: 分割字符串
pattern = r'\W+' # 匹配非单词字符
text = 'hello, world! this is python.'
split_result = re.split(pattern, text)
print("分割后的结果:", split_result)
# 示例5: 使用命名捕获组
pattern = r'(?P<first>\w+) (?P<last>\w+)'
text = 'John Doe'
match = re.search(pattern, text)
if match:
print("第一部分:", match.group('first'))
print("第二部分:", match.group('last'))
^
表示字符串的开头,re.match()
用于从字符串的起始位置进行匹配。\d+
表示一个或多个数字,re.findall()
返回所有匹配的结果。re.sub()
用于将匹配到的模式替换为指定的内容。re.split()
根据指定的正则表达式模式将字符串分割成列表。(?P<name>...)
定义了一个命名捕获组,可以通过 match.group('name')
获取匹配的部分。上一篇:python中len函数
下一篇:python snmp
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站