开发者

How to get numbers from http://www.example.com/images/business/113.jpg

Using regex I need to get the numbers between the last "/" and ".jpg" (this actually might be .png, .gif, etc) in this:

开发者_高级运维

http://www.example.com/images/business/113.jpg

Any ideas?

Thank you


Easy enough using split:

var fileName = myUrl.Split('/')[myUrl.Split('/').Length - 1];
var justTheFileName = fileName.Split('.')[0];


Regular expression are absolute unnecessary here.

Just do:

using System.IO;

var fileName = Path.GetFileNameWithoutExtension("http://www.example.com/images/business/113.jpg");

Take a look at the documentation of the method GetFileNameWithoutExtension:

Returns the file name of the specified path string without the extension.

Edit:
If you still want to use regex for this purpose, the following one will work:

//Both regexes will work here
var pattern = @"/([^/]*)\.jpg"
var pattern2 = @".*/(.*)\.jpg"

var matches = Regex.Matches(pattern, "http://www.example.com/images/business/113.jpg");

if (matches.Count > 0)
    Console.WriteLine(matches[0].Groups[1].Count);

Note:
I didn't compile the regex. This was a small & fast example.


I see that you found a solution matches a single digit in your URL 3 times, but not the entire number. You may want to go with something more "readable" (heh) like this:

(?<=\/)\d+(?=\.\w+$)

If you're trying to capture the number and use it, throw it into a group:

(?<=\/)(\d+)(?=\.\w+$)


Got it!! (?=[\s\S]*?\\.)(?![\s\S]+?/)[0-9]

PS: The regular expression workbench by microsoft KICKS ASS


You could use the following regular expression:

/(?<number>\d+)\.jpg$

It will capture the number into the named group 'number'. The regular expression works as follows:

  1. Search for /
  2. Capture 1 or more times a digit (0-9) to the named group 'number'
  3. Check for .jpg
  4. $ matches the end of the string.

Matching the end makes stuff a lot easier. I don't believe look-ahead or look-behind is necessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜