-
- 正则表达式
- 1.1
match
- 1.2
split
1. 正则表达式
Python通过re模块引入正则表达式的支持。
因为str本身会对\
做转义,一般我们都推荐在定义正则表达式使用r
字符串:
>>> s = "ABC\\-001"
>>> s # 输出 'ABC\\-001'
>>> print(s) # 输出 ABC\-001
>>> s = r"ABC\-001"
>>> print(s) # 输出 ABC\-001
1.1 match
通过re.match
模块,自动在字符串查找匹配的部分:
>>> regex = r"\d{4}-\d{2}-\d{2}"
>>> match = re.match(dt,"2020-09-30")
>>> if match: # 如果有匹配成功的部分,match为True
... print(match.group(0)) # group概念和Java类似,获取匹配的分组,group(0)是获取整个匹配
...
2020-09-30
>>> match = re.match(dt,"2020-09-30aa")
>>> if match: # match并不要求完全匹配,字符串有能能匹配上的部分即可
... print(match.group(0))
...
2020-09-30
>>> match = re.match(dt,"2020-09-aa")
>>> if match:
... print(match.group(0))
... else:
... print("not match") # 找不到匹配上的部分时,match返回的就是Fale了
获取分组:
>>> regex = r"(\d{4})-(\d{2})-(\d{2})"
>>> match = re.match(regex,"2020-09-20")
>>> match.groups()
('2020', '09', '20')
预编译正则:
>>> regex = r"(\d{4})-(\d{2})-(\d{2})"
>>> rc = re.compile(regex)
>>> rc.match("2020-09-20").groups()
('2020', '09', '20')
1.2 split
使用正则表达式切分字符串:
>>> v = r"a b c"
>>> v.split(" ") # 有点时候直接用str的split是不足以完成切分的,比如分隔符有多个
['a', 'b', '', 'c']
>>> re.split(r"\s+",v) # 使用正则切分能解决这个问题
['a', 'b', 'c']
网友评论