re.findall的用法

在import re中,(re.findall(pattern, string, flags=0)):返回string中所有与pattern相匹配的全部字符串,得到数组

r:查找string中出现r标识的字串

>>>import re
>>>text = "https://mp.csdn.net/postedit/82865219"
>>>array = re.findall(r"pos", text)
 
['pos']


^:匹配以^标识开头的字符串
$:匹配以$标识结束的字符串

>>>import re
>>>text1 = "https://mp.csdn.net  wwww "
>>>text2 = "blog.csdn.net"
>>>array1 = re.findall(r"^https", text1)
   array2 = re.findall(r"^https", text2)
   array3 = re.findall(r"$net", text1)
   array4 = re.findall(r"$net", text2)
 
array1 = ['https']
array2 = []
array3 = []
array4 = ['net']


[]:匹配括号中的其中一个字符

>>>import re
>>>text = "I am so happy! "
>>>array1 = re.findall("[a-zA-Z]", text)
   array2 = re.findall("[a-zA-Z]+", text)
 
array1 = ['I', 'a', 'm', 's', 'o', 'h', 'a', 'p', 'p', 'y']
array2 = ['I', 'am', 'so', 'happy']

\d:匹配0到9之间的数字
\D:匹配除0到9之外的字符

>>>import re
>>>text = "https://mp.csdn.net/postedit/82865219"
>>>array1 = re.findall("\d", text)
   array2 = re.findall("\d\d", text)
   array3 = re.findall("\D", text)
   array4 = re.findall("\D+", text)
 
array1 = ['8', '2', '8', '6', '5', '2', '1', '9']
array2 = ['82', '86', '52', '19']
array3 = ['h', 't', 't', 'p', 's', ':', '/', '/', 'm', 'p', '.', 'c', 's', 'd', 'n', '.', 'n', 'e', 't', '/', 'p', 'o', 's', 't', 'e', 'd', 'i', 't', '/']
array4 = <class 'list'>: ['https://mp.csdn.net/postedit/']

 

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐