Extract file extension: Difference between revisions

Content added Content deleted
(→‎Task: improve formatting and wording)
(→‎{{header|Perl 6}}: replace the solution with a simpler one, and mention the built-in ".extension" method)
Line 793: Line 793:


=={{header|Perl 6}}==
=={{header|Perl 6}}==
<lang perl6>sub extension ( Str $filename --> Str ) {
given $filename.split(/\./)[*-1] {
when $filename { "" }
when / <[\/_]> / { "" }
default { "." ~ $_ }
}
}


The built-in <code>.IO.extension</code> method can be used, but it...
say "$_ -> ", extension($_).perl for (
* doesn't include the dot in the output
* doesn't restrict extensions to letters and numbers.

Here's a custom implementation which does satisfy those requirements:

<lang perl6>sub extension (Str $filename --> Str) {
$filename.match(/:i ['.' <+alpha-[_]>+]? $ /).Str
}</lang>

Testing:

<lang perl6>say "$_ -> {(extension $_).perl}" for
'mywebsite.com/picture/image.png',
'mywebsite.com/picture/image.png',
'http://mywebsite.com/picture/image.png',
'http://mywebsite.com/picture/image.png',
Line 808: Line 813:
'/path/to.my/file',
'/path/to.my/file',
'file.odd_one',
'file.odd_one',
)</lang>
;</lang>

{{out}}
{{out}}
<pre>
<pre>