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

Time:12-28

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)

CodePudding user response:

It is possible like this:

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

Python-3.8 required for assignment expressions.

CodePudding user response:

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.

  • Related