re.search() method in Python helps to find patterns in strings. It scans through the entire string and returns the first match it finds. This method is part of Python's re-module, which allows us to work with regular expressions (regex) simply. Example:
Python
import re
s = "Hello, welcome to the world of Python."
pat = "welcome" # pattern
res = re.search(pat, s) # search pattern
if res:
print("Yes")
else:
print("No")
Explanation: This code searches the entire string to find if the pattern "welcome" exists. If a match is found, it confirms the presence by printing "Yes" otherwise, it prints "No".
Syntax of re.search()
re.search(pattern, string, flags=0)
Parameters:
- pattern: A regex pattern to search for; can be simple text or a complex expression.
- string: The target string where the pattern is searched.
- flags (optional): Modifiers that change matching behavior (e.g., case-insensitive); default is 0.
Returns:
- Match object: Returned if a match is found; provides methods like .group() and .start().
- None: Returned if no match is found.
Examples of re.search()
Example 1: In this example, we search for the first number that appears in a given string using a regular expression. It support special characters like \d for digits, \w for word characters and more, allowing us to search for complex patterns efficiently.
Python
import re
s = "I have 2 apples and 10 oranges."
pat = r"\d+" # match digits
res = re.search(pat, s) # search pattern
if res:
print(res.group())
else:
print("No")
Explanation: This code searches for the first occurrence of one or more digits in the string. The pattern \d+ matches one or more digits and re.search() returns the first match it finds.
Example 2: In this example, we search for a phone number in a string using a regular expression pattern. A match object returned by the search provides useful methods like group() to get the matched text and start() to find the starting index of the match in the original string.
Python
import re
s = "My phone number is 123-456-7890."
pat = r"\d{3}-\d{3}-\d{4}" # match phone number format
res = re.search(pat, s) # search pattern
if res:
print(res.group()) # matched number
print(res.start()) # match start index
else:
print("No")
Explanation: This pattern matches a phone number in the format 123-456-7890. The group() method returns the matched string and start() gives the index at which the match begins.
Example 3: In this example, we want to check whether the given string begins with a capital letter (A–Z). We're using the re.search() function along with a regular expression pattern that looks for a capital letter at the beginning of the string.
Python
import re
s = "Python is great"
pat = r"^[A-Z]" # match capital letter at start
res = re.search(pat, s) # search pattern
if res:
print(res.group())
else:
print("No")
Explanation: This pattern ^[A-Z] checks if the string starts with an uppercase letter. If it does, group() returns that letter otherwise, "No" is printed.
Related Articles:
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Support Vector Machine (SVM) Algorithm Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read