0

I have list of patterns and I need to return that pattern if that is present in the given string else return None. I tried with the below code using re module , but I am getting only null in "matches" (when I tried to print matches). Completely new to corepython and regex,kindly help

import re
patterns_lst=['10_TEST_Comments','10_TEST_Posts','10_TEST_Likes']

def get_matching pattern(filename):
   for pattern in patterns_lst:
     matches = re.(pattern,filename)
   if matches:
      return matches
   else:
      return None

print(get_matching pattern("6179504_10_TEST_Comments_22-Nov-2021_22-Nov-2021.xlsx"))
6
  • 1
    This isnt even valid python. Is this a homework excercise where you have been given some code and you are meant to fix the code and make it work? Commented Dec 24, 2021 at 9:56
  • I will happy to help you if you provide code that I could run (and is similar enough to this one) ;) Commented Dec 24, 2021 at 9:57
  • @ChrisDoyle definitely this not home work code , I have to pull the report of names from a SFTP server and re-name it accordingly with the matching pattern and sent it via DRF response . The files patterns are almost same , here i just replaced the original file names with "sample" and "test" Commented Dec 24, 2021 at 10:04
  • @kosciej16 you want it has attachment ? Commented Dec 24, 2021 at 10:06
  • @SivaPerumal Your code doesn't run, it has various syntax errors. Commented Dec 24, 2021 at 10:06

1 Answer 1

1

I have made some changes to your function:

def get_matching_pattern(filename):            ## Function name changed
    for pattern in patterns_lst:
        match = re.search(pattern, filename)   ## Use re.search method

        if match:                              ## Correct the indentation of if condition
            return match                       ## You also don't need an else statement

Output:

>>> print(get_matching_pattern("6179504_10_TEST_Comments_22-Nov-2021_22-Nov-2021.xlsx"))
<re.Match object; span=(8, 24), match='10_TEST_Comments'>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.