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 to match specific number

I currently have the regex "(?<!mp){i}" which matches a specific number but it overmatches and includes 10, 11, 21, etc when I want to match 1. In short, it is matching as long as i contains the number in the string (if i=2 and the string contains "xxxxxx 24" it would also match, which I don’t want)

strings

xx 1.mp4
xx 10.mp4
xx21.mp4
xx1.mp4
xx 1 xx.mp4
xx.1.xxx.mp4
xx.11.xxx.mp4
xxx s1e3 xxx.mp4
xxx season 1 episode 3
xxx season 2 episode 1

expected outcome if trying to match where i=1

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

xx 1.mp4
xx1.mp4
xx 1 xx.mp4
xx.1.xxx.mp4
xxx season 2 episode 1

note: xxx s1e3 xxx.mp4 and xxx season 1 episode 3 was NOT match even though it contains 1 because it was followed by s and season. However, xxx season 2 episode 1 Should be match, since the "episode" contains 1

Another note: Ideally, it shouldn’t be limited to just 1, since I wouldn’t want to match 24 32 when I am trying to find a match for i=2, etc

I’ve tried

if re.search(rf"(?<!mp){i}", string):
                do something

it returns strings with 10,11, 21 100, etc when I am just searching for 1. Likewise with i=2

>Solution :

You can use negative lookaheads and lookbehinds to ensure that the number is not adjacent to any other digits.

if re.search(rf"(?<!\d){i}(?!\d)", string):
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