Regex for finding substring that starts with # and end with space in python

The re.findall function will return a list of all matches found in the string. In this case, it will capture the digits following the ‘#’ and ending before the space.

Here’s the complete code:

import re

x = 'XYZ (ABC) #1234325 ACC:14532532'
pattern = r'#(\d+)\s'
substrings = re.findall(pattern, x)
print(substrings)  # Output should be ['1234325']

The output will be [‘1234325’]. If you need just the string and not a list, you can extract the first element from the list:

if substrings:
    print(substrings[0])  # Output should be '1234325'

Read more here: Source link