0

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

3
  • 8
    Many languages have built-in ways of handling filenames and extensions. What are you using? Commented Jul 20, 2010 at 17:18
  • 2
    Doesn't the language/platform you are using to run regexes have file handling routines? Commented Jul 20, 2010 at 17:19
  • I'm curious: why are you writing tXt every time, rather than txt? Commented Jul 20, 2010 at 18:32

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

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.)

Comments

0

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.

Comments

-2
/^(.*?)\.(.*)$/

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

4 Comments

I'm, and a.file.name.tXt not just tXt
In which case remove the greedy match at put it on the second group. You said you only wanted 'tXt'.
The ? makes a quantifier lazy, not greedy!
Based on your comment, you possibly misunderstand greedy vs lazy matching. Read more at 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.