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

Is it a way to capture text as 'internal variables' in regex?

So i have these string test1string2 , test2string2 and test3string3.

Regex "test/dstring/d" would capture the three of them, but is there a way to write a regex that will capture only the second and third strings? Sort of: capture "test" followed by any number followed by "string" followed by a number but only if those numbers are the same.

I am working in python if it adds relevant info

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 :

You are looking for backreference in python‘s re it is backslash followed by number of capturing group, consider following simple example

import re
texts = ['A1A1','A1B2','A1C1']
for t in texts:
    if re.match(r'[A-Z](\d)[A-Z]\1',t):
        print(t)

gives output

A1A1
A1C1
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