Discuss if a string matches a regex... in the Python Programming forum on Dev Shed. if a string matches a regex... Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
Time spent in forums: 9 h 2 m 21 sec
Reputation Power: 0
if a string matches a regex...
Im trying to work out if a string 'fits' a regular expression.
I have the regular expression '/(\w+/)*(\w+).(\w+)' and if a string 'matches' it then i would like it to return true, else if it doesnt return false.
I was thinking something along the lines of:
path = """/path/to/file.jpg"""
r = r'/(\w+/)*(\w+).(\w+)'
ext_r = re.compile(r)
ext = ext_r.findall(path)
but i cannot find out how to tell if the string exactly matches the expression, I can only print it.
Correct me if im wrong but it should find expressions like '/directory/file.ext' with many directory levels and one file.ext at the end.
for instance i have the string /absolute/path/image.jpg and the regex should find this then return true, else if the string was:
'/alsolute/path/image' or '/absolute/path' or 'abolsolute/path/image.jpg' then it should return false.
Sorry, i am totally new to both python and regex and I have tried the re methods, but i just get object links returned to me.
Time spent in forums: 3 Days 6 h 10 m 21 sec
Reputation Power: 34
is there a way of make all portions of the regex statement compulsory. i.e. the path must have a "file.jpg" portion as well as "/" (root) and then *possibly* a directory in the form of "directory/".
What if the file has no extension?
What if it is file.jpg.vbs?
What if the system is one where / isn't the path separator?
What if the directory name has spaces or dots in the name?
Does the path have to actually exist on the system?
Do you care about invalid characters for a real path - e.g. Windows wont allow <>\? and so on in file or folder names...
pattern = "^/(.+\/)*(.+)$"
A string starting with a /
(Optionally followed by:
One or more characters and a /)
Repeated as many times as possible
Ending in one or more characters.
"/a" or "/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/a"
Is that what you're looking for?
I think you will have to do the True/False yourself with:
if re.match(pattern, text):