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

What's wrong with my regex using lookahead and lookbehid to identify the numbers

I am trying to identify the 10 digit number in a directory name, which may look like this: d:\research\python\test\2020\0001766016-20-000002.txt

My code is as follows:


import re
text="d:\research\python\test\2020\0001766016-20-000002.txt"
x=re.search(r"(?<=\\)\d{10}(?=-)",text)
print(x)

I got None as a result. Any suggestions?

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 issue is with your string that contains \

You need to encapsulate the string like this r'd:\research\python\test\2020\0001766016-20-000002.txt'

import re as regex

text = r'd:\research\python\test\2020\0001766016-20-000002.txt'

x = regex.search(r"(?<=\\)\d{10}(?=-)", text)
print(x.group(0))
0001766016

reference: https://www.pythontutorial.net/python-basics/python-raw-strings/

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