
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
The search Function in Python
This function searches for first occurrence of RE pattern within string with optional flags.
Syntax
Here is the syntax for this function −
re.search(pattern, string, flags=0)
Here is the description of the parameters −
Sr.No. | Parameter & Description |
---|---|
1 | pattern This is the regular expression to be matched. |
2 | string This is the string, which would be searched to match the pattern at the beginning of string. |
3 | flags You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below. |
The re.search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get matched expression.
Sr.No. | Match Object Method & Description |
---|---|
1 | group(num=0) This method returns entire match (or specific subgroup num) |
2 | groups() This method returns all matching subgroups in a tuple (empty if there weren't any) |
Example
#!/usr/bin/python import re line = "Cats are smarter than dogs"; searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) if searchObj: print "searchObj.group() : ", searchObj.group() print "searchObj.group(1) : ", searchObj.group(1) print "searchObj.group(2) : ", searchObj.group(2) else: print "Nothing found!!"
Output
When the above code is executed, it produces the following result −
searchObj.group() : Cats are smarter than dogs searchObj.group(1) : Cats searchObj.group(2) : smarter
- Related Articles
- What is the search() function in Python?
- Significance of regex match() and regex search() function in Python
- Word Search in Python
- Recursive function to do substring search in C++
- Linear Search in Python Program
- Binary Search (bisect) in Python
- Search and Replace in Python
- Explain Binary Search in Python
- Word Search II in Python
- How to Apply the Reverse Find or Search Function in Excel?
- Search a string in Matrix Using Split function in Java
- Validate Binary Search Tree in Python
- Search in Rotated Sorted Array in Python
- The dir( ) Function in Python
- The match Function in Python

Advertisements