re.search()
What You'll Learn: In this tutorial, you'll discover how to use the re.search() function to find the first match of a pattern in a string. This function helps you locate specific patterns quickly.
Syntax
The syntax of the re.search() function is:
python
re.search(pattern, string, flags=0)
Parameters
- pattern (required): The pattern to be found in the string.
- string (required): The string in which the pattern is to be found.
- flags (optional): Optional flags like
re.IGNORECASE.
Return Value
The function returns a re.Match object if a match is found; otherwise, it returns None.
Examples
- Finding a Pattern in a String
Example Code:
pythonimport re pattern = '[a-z]+' string = '-----2344-Hello--World!' result = re.search(pattern, string) print(result)Output:
<re.Match object; span=(11, 15), match='ello'>
- Getting the Matching Text
- To get the matching text as a string, use the
group()method on there.Matchobject. Example Code:
pythonimport re pattern = '[a-z]+' string = '-----2344-Hello--World!' result = re.search(pattern, string) print(result.group())Output:
ello
- To get the matching text as a string, use the
- Pattern Not in String
- When the pattern is not present in the string,
re.search()returnsNone. Example Code:
pythonimport re pattern = '[a-z]+' string = '-----2344-HELLO--WORLD!' result = re.search(pattern, string) print(result)Output:
None
- When the pattern is not present in the string,
Try It Yourself: Fun Exercises
- Find a Word:
- Create a string and a pattern representing a word.
- Use
re.search()to find the first occurrence of the word in the string.
- Match Digits:
- Write a string containing numbers and letters.
- Use
re.search()to find the first sequence of digits in the string.
Summary:
In this Python tutorial, we learned how to use the re.search() function to find the first match for a given pattern in a string. This function is useful for locating specific patterns quickly. Keep experimenting and have fun with Python!