regex findall function in python example

regex findall function in python example

findall() function return a list of all non overlapping matches of the pattern in the string. However, it'll return a list of tuples where each tuple represents a match and contains the betrothed groups, If the pattern contains groups( defined using hiatuses).

The basic syntax of re.findall() is as follows:

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

Breakdown function Arguments:

pattern: A string representing the regular expression pattern you want to search for.

string: The input string where you want to find the pattern.

flags (optional): Additional flags that modify the pattern's behavior. You can use constants from the re module, such as re.IGNORECASE for case-insensitive matching.

Code 1:

import re
string = "Hello, my name is Arsalan. I have 1 Youtube Channel."
pattern = r'\d+'
matches = re.findall(pattern, string)
print(matches)

Output:

['1']

Code 2:

import re
string = "Hello, my name is Arsalan. I have 1 Youtube Channel."
pattern = r'\bA.*n\b'
find = re.findall(pattern,string)
print(find)

Output:

['Arsalan']

Code 3:

import re
string = "Hello, my name is Arsalan. I have 1 Youtube Channel."
pattern = r'Hello'
words = re.findall(pattern, string)
print(words)

Output:

['Hello']