Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I have a string from which I want to pull out a substring that starts with ‘#’ and end with ‘space’ i.e. /s in python using ‘re’ module

I tried below but it doesn’t work

import re
x = 'XYZ (ABC) #1234325 ACC:14532532'
pattern = r'^#./s$'
substrings = re.findall(pattern, x)
print(substrings)


#Output should be '1234325'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading