tuoheng_algN/test/正则/re.py

146 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
'''
1.匹配某个字符串
match():只能匹配某个
'''
# text = 'python python'
# result = re.match('py', text)
# print(result)
# print(result.group())
'''
2.点
匹配任意的某个字符【无法匹配换行符】【必须从开头开始匹配】
'''
# text = 'python'
# result = re.match('.', text)
# print(result)
# print(result.group())
'''
3.\d
匹配任意的数字【除了数字外均无法匹配】
'''
# text = '1python'
# result = re.match('\d', text)
# print(result)
# print(result.group())
'''
4.\D
除了数字外均可匹配【数字均无法匹配】
'''
# text = 'python'
# result = re.match('\D', text)
# print(result)
# print(result.group())
'''
5.\s
匹配空白字符【\n\t\r 、空格】
'''
# text = '\npython'
# result = re.match('\s', text)
# print(result)
# print(result.group())
'''
6.\w
匹配小写的a-z大写的A-Z数字和下划线
'''
# text = 'python'
# result = re.match('\w', text)
# print(result)
# print(result.group())
'''
7.\W
匹配除小写\w之外的所有字符
'''
# text = '\npython'
# result = re.match('\W', text)
# print(result)
# print(result.group())
'''
8.[] ->> 组合的方式
只要在中括号内的内容均可匹配
'''
# text = '\npython'
# result = re.match('[\n_]', text)
# print(result)
# print(result.group())
'''
9.星号 *
匹配零个或者多个字符
'''
# text = '139-1234-5678'
# result = re.match('[-\d]*', text)
# print(result)
# print(result.group())
'''
10.加号 +
匹配1个或者多个字符
'''
# text = '139-1234-5678'
# result = re.match('[-\d]+', text)
# print(result)
# print(result.group())
'''
11.问号
匹配0个或者匹配1个
'''
# text = '139-1234-5678'
# result = re.match('[-\d]?', text)
# print(result)
# print(result.group())
'''
12. {m,n} 匹配m到n个
匹配0个或者匹配1个
'''
# text = '139-1234-5678'
# result = re.match('[-\d]{1,5}', text)
# print(result)
# print(result.group())
'''
13. 匹配所有的数字
'''
# text = '139-1234-5678'
# result = re.match('[-0-9]*', text)
# print(result)
# print(result.group())
'''
14. 匹配所有的非数字
'''
# text = '139-1234-5678'
# result = re.match('[^0-9]*', text)
# print(result)
# print(result.group())
# re.match() 必须从字符串开头进行匹配
# re.search() 从左到右进行字符串的遍历,找到就返回
# text = 'aapython'
# result = re.match('py', text)
# print(result)
# print(result.group())
# text = 'aapython'
# result = re.search('py', text)
# print(result)
# print(result.group())
"""
1. 贪婪模式: 正则表达式会尽可能多地匹配字符【默认就是贪婪模式】
2. 非贪婪模式: 正则表达式会尽可能少地匹配字符【?】
转义字符 \
"""