字符串的拆分方法 及 match和search 方法的不同

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_37189082/article/details/100303093

1. 字符串的拆分方法有哪些?

string对象的split方法,不允许有多个分隔符

函数 re.split(),允许为分隔符指定多个正则模式即可以同时输入多个分隔符对目标字符串进行拆分。

line = "I am super man!"
# 以空格分隔符进行拆分字符串
print(line.split(" "))     # string的split方法
import re
print(re.split(" ", line)) # re模块的split方法

# 同时以空格或m分隔符进行拆分字符串
print(line.split("[ m]"))     # 已完整字符串显示,并没有拆分
print(re.split("[ m]", line))

输出结果:

['I', 'am', 'super', 'man!']

['I', 'am', 'super', 'man!']

['I am super man!']

['I', 'a', ' ', 'super', ' ', 'an!']

2. re模块中 match和search 方法的不同

search,扫描整个字符串查找匹配并返回第一个成功的匹配

match,只在字符的开始位置匹配,如果不是起始位置匹配成功的话,match()就返回none。

import re

s1 = "helloworld, helloworld"
w1 = 'hello'
w2 = 'world'

# 查询 hello 是否在s1中
print(re.search(w1, s1))         # search扫描整个字符串
print(re.search(w1, s1).group()) # 调用group()方法输出查询结果

print(re.match(w1, s1))          # match只在字符串开始的位置匹配
print(re.match(w1, s1).group())

# 查询 world 是否在s1中
print(re.search(w2, s1))         
print(re.search(w2, s1).group()) 

print(re.match(w2, s1))            # 返回None
print(re.match(w2, s1).group())    # 会报错空对象是没有方法的

输出结果:

<_sre.SRE_Match object; span=(0, 5), match='hello'>

hello

<_sre.SRE_Match object; span=(0, 5), match='hello'>

hello

<_sre.SRE_Match object; span=(5, 10), match='world'>

world

None

Traceback (most recent call last):

File "test1.py", line 19, in <module>

print(re.match(w2, s1).group())

AttributeError: 'NoneType' object has no attribute 'group'

猜你喜欢

转载自blog.csdn.net/qq_37189082/article/details/100303093