深度阅读

How to use the re.findall() function to find all matching substrings in a string?

作者
作者
2023年08月22日
更新时间
7.45 分钟
阅读时间
0
阅读量

To use the re.findall() function in Python to find all matching substrings in a string using regex, you can pass a regular expression pattern as the first argument to re.findall(), and the target string as the second argument. For example:

import re

pattern = r'\d+'  # regex pattern to match one or more digits
text = 'I have 3 apples and 2 oranges'
matches = re.findall(pattern, text)

print(matches)  # Output: ['3', '2']

This will return a list of all the non-overlapping matches of the regex pattern in the given string. In this case, the regex pattern \d+ matches one or more digits in the text, so the output will be ['3', '2']. You can modify the regex pattern to match different types of substrings in the string.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。