A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_re_search_method.htm below:

Python re.search() method

Python re.search() method

The Python re.search() method is used to search for a pattern within a string. It scans the entire string by returning a match object if it finds the pattern anywhere in the string.

Unlike the re.match() method which only checks for matches at the beginning of the string where as re.search() looks for matches anywhere in the string. If a match is found it returns the match object otherwise it returns 'None'.

This method is useful for finding patterns in strings regardless of their position, allowing for more flexible pattern matching and extraction of information from text data.

Syntax

Following is the syntax and parameters of Python re.search() method −

re.search(pattern, string, flags=0)
Parameters

Following are the parameter of the python re.search() method −

Return value

This method returns the match object if the pattern is found in the string otherwise it returns None.

Example 1

Following is the basic example of using the re.search() method. Here the pattern 'world' is searched within the string 'Hello, world!' −

import re

pattern = re.compile(r'\d+')
match = pattern.search('123abc')
if match:
    print(match.group())  
Output
123
Example 2

Here in this example the pattern '\d+-\d+-\d+' is used to match a date format and capturing groups are utilized to extract year, month and day separately −

import re

result = re.search(r'(\d+)-(\d+)-(\d+)', 'Date: 2022-01-01')
if result:
    print("Year:", result.group(1))  
    print("Month:", result.group(2)) 
    print("Day:", result.group(3))  
Output
Year: 2022
Month: 01
Day: 01
Example 3

In this example ?<=good is a positive look behind assertion that checks for the presence of 'good' before 'morning' without including it in the match −

import re

result = re.search(r'(?<=good )morning', 'Have a good morning!')
if result:
    print("Pattern found:", result.group())  
Output
Pattern found: morning

python_modules.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4