deadfish
deadfish

Reputation: 12304

Regex between, from the last to specific end

Today my wish is to take text form the string. This string must be, between last slash and .partX.rar or .rar

First I tried to find edge's end of the word and then the beginning. After I get that two elements I merged them but I got empty results.

String:

http://hosting.xyz/1234/15-game.part4.rar.html

http://hosting.xyz/1234/16-game.rar.html

Regex:

Begin:(([^/]*)$) - start from last /

End:(.*(?=.part[0-9]+.rar|.rar)) stop before .partX.rar or .rar

As you see, if I merge that codes I won't get any result. What is more, "end" select me only .partX instead of .partX.rar

All what I want is: 15-game.part4.rar and 16-game.rar


What i tried:

(([^/]*)$)(.*(?=.part[0-9]+.rar|.rar))

(([^/]*)$)

(.*(?=.part[0-9]+.rar|.rar))

I tried also

/[a-zA-Z0-9]+

but I do not know how select symbols.. This could be the easiest way. But this select only letters and numbers, not - or _. If I could select symbols..

Upvotes: 2

Views: 190

Answers (4)

fge
fge

Reputation: 121712

Use two regexes:

  • start to substitute .*/ with nothing;
  • then substitute \.html with nothing.

Job done!

Upvotes: 0

anubhava
anubhava

Reputation: 784998

I'm not a C# coder so can't write full code here but I think you'll need support of negative lookahead here like this:

new Regex("/(?!.*/)(.+?)\.html$");

Matched Group # 1 will have your string i.e. "16-game.rar" OR "15-game.part4.rar"

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

Nothing could be simpler! :-)

Use this:

new Regex("^.*\/(.*)\.html$")

You'll find your filename in the first captured group (don't have a c# compiler at hand, so can't give you working sample, but you have a working regex now! :-) )

See a demo here: http://rubular.com/r/UxFNtJenyF

Upvotes: 1

user554546
user554546

Reputation:

You don't really need a regex for this as you can merely split the url on / and then grab the part of the file name that you need. Since you didn't mention a language, here's an implementation in Perl:

use strict;
use warnings;

my $str1="http://hosting.xyz/1234/15-game.part4.rar.html";

my $str2="http://hosting.xyz/1234/16-game.rar.html";

my $file1=(split(/\//,$str1))[-1]; #last element of the resulting array from splitting on slash

my $file2=(split(/\//,$str2))[-1];

foreach($file1,$file2)
{
  s/\.html$//; #for each file name, if it ends in ".html", get rid of that ending.
  print "$_\n";
}

The output is:

15-game.part4.rar
16-game.rar

Upvotes: 1

Related Questions