Trying to dynamically use regex findall to pick up registry keys. How to append single escape to regex string?

Viewed 25

test_str = Monitor for deletion of Windows Registry keys and/or values related to services and startup programs that correspond to security tools such as HKLM:\\SOFTWARE\\Microsoft\\AMSI\\Providers. Monitor for changes made to Windows Registry keys and or values related to services and startup programs that correspond to security tools such as HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows Defender.

for path_found in iocs_found['windows_path']:
   path_found = path_found.replace('\\', '\\\\')
   print(path_found)
   regex_pattern = f"[A-Z]+(?:{path_found})" 
   matches = re.findall(regex_pattern, test_str)
   print(matches)
   print('\n')

print statements are:

M:\SOFTWARE\Microsoft\AMSI\Providers.

['HKLM:\SOFTWARE\Microsoft\AMSI\Providers.']

M:\SOFTWARE\Policies\Microsoft\Windows

['HKLM:\SOFTWARE\Policies\Microsoft\Windows']

Two questions:

  1. how do I change my regex code so that HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows becomes HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows Defender
  2. how to add a new regex to the current dynamic regex so that there aren't double escapes?

Please help.

1 Answers

For the particular input you showed above, the pattern HKLM:\\.*?(?=\.) should work:

test_str = "Monitor for deletion of Windows Registry keys and/or values related to services and startup programs that correspond to security tools such as HKLM:\\SOFTWARE\\Microsoft\\AMSI\\Providers. Monitor for changes made to Windows Registry keys and or values related to services and startup programs that correspond to security tools such as HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows Defender."
matches = re.findall(r'HKLM:\\.*?(?=\.)', test_str)
print(matches)

This prints:

['HKLM:\\SOFTWARE\\Microsoft\\AMSI\\Providers',
 'HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows Defender']
Related