1

Hi I need a regex that gets the extension of a path, but if it doesnt have an extension it shows nothing or the word "Blank"(<-preferred output)

Here is what I have it works great for paths with extensions but if the path doesnt have an extension I get a full path name showing up when I export to CSV

What I have: Extension = $matches.fullname -replace '..(.)','$1'

Example

\Server\ShareFile\RootFolder1.2.3\Folder1.2.3\Subfolder2\Excel.csv

In this case it would get just .csv

\Server\ShareFile\RootFolder1.2.3\Folder1.2.3\Subfolder2\RandomFileNoExtension

In this case it would show nothing or if possible "Blank"

user3862909
  • 13
  • 1
  • 4

2 Answers2

7

Use this regex:

\.[^.]+$

Sample Usage

if ($filename -cmatch '\.[^.]+$') {
    $extension = $matches[0]
}

Explanation

  • \. matches a dot
  • [^.]+ matches chars that are not a dot
  • The $ anchor asserts that we are at the end of the string
zx81
  • 41,100
  • 9
  • 89
  • 105
  • You arrived first ! :( Anyway nice answer – Valentin Mercier Jul 30 '14 at 21:17
  • This is for a creating a new object in an hash table so using an IF statement doesn't flow well, I should of put that in the post sorry. – user3862909 Jul 30 '14 at 21:29
  • @user3862909 My focus is on giving you the right regex, I trust you to write the code you need. :) The code sample is just to show an example of using the regex. – zx81 Jul 30 '14 at 21:33
0

You can solve this problem without using a regex. Use [System.IO.Path]::GetExtension($fileName).

[System.IO.Path]::GetExtension("README.md")
  returns .md

[System.IO.Path]::GetExtension("README")
  returns nothing

You can find more info on MSDN.

Casey
  • 3,307
  • 1
  • 26
  • 41
  • I used this and I got the same output at what I was using, Although yours looks more aesthetic so I will be using that for now =) – user3862909 Jul 30 '14 at 21:28