Is it possible to print the match of a re.search() used in an if statement?

Question:

I need to keep my regex search in an if statement. Is it possible to get the match of my re.search() like this?

if re.search(regex,string):
    print(match)
Asked By: blahahaaahahaa

||

Answers:

It is possible like this:

if match := re.search(regex,string):
    print(match)

Python-3.8+ required for assignment expressions.

Answered By: wim
import re

my_string = "abcdefcddd"
if re.search('c', my_string):
    print("A match found.")
else:
    print('No match')
#or
found = re.search('c', my_string)
print(found.group())
print(found.span()) #index of the first match

My guess you may need re.findall() or its sister re.finditer() if you want to find all the regex matches.

matches = re.findall('c', my_string)
print(matches)

matches = re.finditer('c', my_string)
for match in matches:
    print(match)

Maybe check and see what exactly you need. Python documentation should help.

Answered By: Supertech
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.