tags:

views:

80

answers:

4

How do I determine the file extension of a file name string?

lets say I have

I'm.a.file.name.tXt

the regex should return tXt

A: 
/^(.*?)\.(.*)$/

The '?' makes it greedy. Your result will be in the second group.

Thomas O
I'm, and a.file.name.tXt not just tXt
DerNalia
In which case remove the greedy match at put it on the second group.You said you only wanted 'tXt'.
Thomas O
The `?` makes a quantifier **lazy**, *not* greedy!
Peter Boughton
Based on your comment, you possibly misunderstand greedy vs lazy matching. Read more at http://www.regular-expressions.info/repeat.html but basically, if taking this approach, you want `(greedy).(lazy)` in order to consume as much as possible for the first group and as little as required for the second.
Peter Boughton
+2  A: 

something like \.[^.]*$ should do it

Scharron
As an extension, you possibly want make to the `\.` a lookbehind - so `(?<=\.)[^.]*$` - to avoid potentially having to remove the `.` later. Though not all regex implementations support lookbehinds, and we don't know what one this is for.
Peter Boughton
A: 

What language is this in? It's quite possible you don't want to actually use a regex - assuming the name is a String you'll probably just want to do something like split it over periods and then choose the last segment. Okay, that's sort of a regex answer, but not a proper one.

Stephen
+1  A: 

You probably don't need regex - most languages will have the equivalent to this:

ListLast(Filename,'.')

(If you do need regex for some reason, Scharron's answer is correct.)

Peter Boughton