Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python re.findall() method



The Pythonre.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings. If the pattern includes capturing groups thenre.findall() returns a list of tuples containing the matched groups.

There.findall() method takes three arguments such as the pattern, the string to search and flags to modify the search behavior.

The methodsre.search() orre.match() which return only the first match whereas methodre.findall() finds all matches by making it useful for extracting multiple instances of a pattern from a text.

Syntax

Below are the syntax and parameters of Pythonre.findall() method −

re.findall(pattern, string, flags=0)

Parameters

Following are the parameters of the pythonre.findall() method −

  • pattern: The regular expression pattern to search for.
  • string: The string to search within.
  • flags(optional): These flags modify the matching behavior

Return value

This method returns a list of all non-overlapping matches of the pattern in the string.

Example 1

Following is the basic example of using there.findall() method. In this example the pattern '\d+' is used to find all numeric sequences in the string and the methodre.findall() returns a list of all matches −

import reresult = re.findall(r'\d+', 'There are 123 apples and 456 oranges.')print(result)

Output

['123', '456']

Example 2

In this example the pattern '\b\w+\b' is used to find all words in the string. It returns a list of words −

import reresult = re.findall(r'\b\w+\b', 'Hello, world! Welcome to Python.')print(result)

Output

['Hello', 'world', 'Welcome', 'to', 'Python']

Example 3

Here in this examplere.MULTILINE flag allows '^' to match the start of each line in a multiline string. There.findall() method returns all matches from each line −

import retext = """HellohelloHELLO"""result = re.findall(r'^hello', text, re.IGNORECASE | re.MULTILINE)print(result)

Output

['Hello', 'hello', 'HELLO']
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp