Here's the problem.
I'm using pythons re-functions.

I'm supposed to make a re-function to check if a string
ends with 3 numbers(or more) before the extension.(e.g. 123.txt, 93821.ini)

Here's my code that's supposed to do the magic

re.search('[0-9][0-9][0-9]\.','1234.txt')

now, this doesn't work out. And I have no clue why not.
I reccon it's the "\." that doesn't work properly since;

re.search('[0-9][0-9][0-9]_','1234_txt')

works perfectly.

Dani AI

Generated

The confusion here was not a Python bug but how regular expressions treat the dot and how the pattern is anchored. As pointed out, an unescaped . matches any single character; escaping it (\.) makes it a literal dot. For filenames the intent is usually "three or more digits immediately before the final extension", so the pattern must require digits, then a literal dot, then the extension, and the match should be anchored to the end of the string.

A compact single-regex that enforces that is:

import re

pattern = re.compile(r'\d{3,}\.[^.]+$')
bool(pattern.search(filename))

Explanation: \d{3,} requires at least three digits, \. matches the literal separator, [ ^.]+$ (no-dot class) consumes the extension up to the end of the string so the digits are directly before the final extension.

A robust alternative is to split the path and extension first, then test the base name. This avoids surprises with directories or multi-dot paths:

import os, re

base = os.path.splitext(os.path.basename(path))[0]
bool(re.search(r'\d{3,}$', base))

Notes and pitfalls: prefer raw-string literals (r'...') to avoid backslash issues; use os.path.basename on full paths; re.match only checks the start of the string while re.search scans the whole string; compile the pattern if checking many filenames. If multi-extensions (like .tar.gz) must be handled differently, split on dots or peel extensions iteratively.

Recommended Answers

All 4 Replies

It seems to work here...

import re

print re.findall('[0-9][0-9][0-9]\.', '1234_.txt')
print
print re.findall('[0-9][0-9][0-9]\.', '1234.txt')

Can you explain what's not working.

Cheers and Happy coding

Thanks for the reply

oh, I thought that "." without the \ meant any symbol

so if i wrote:

re.search('[0-9][0-9][0-9]\.','1234atxt')

would work too. But now I see that it doesn't. Why is that? :S

You are write, just not implementing good.

Because as you say, if you don't escape the '.' it will match any simbol, and so...

re.search('[0-9][0-9][0-9].','1234atxt')

will work. But as you 'escaped' it using the '\' it matchs the '.'.

Cheers and happy coding

Great! Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.