How to use the re.search() function to search for a pattern in a string?
Published on Aug. 22, 2023, 12:18 p.m.
While the previous search results are informative, I can provide an answer to the suggested question for completeness.
To use the re.search()
function in Python to search for a regex pattern in a string, you can pass the pattern as the first argument to re.search()
, and the target string as the second argument. For example:
import re
pattern = r'\d+' # regex pattern to match one or more digits
text = 'I have 3 apples and 2 oranges'
match = re.search(pattern, text)
if match:
print(match.group()) # Output: '3'
This will return the first non-overlapping occurrence of the regex pattern in the given string. In this case, the regex pattern \d+
matches one or more digits in the text, so the output will be '3'
. If the pattern is not found in the string, re.search()
will return None
.