Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to get facebook profile

Tags:

c#

regex

I tried to check matches facebook url and get profile in one regular expression: I have:

http://www.facebook.com/profile.php?id=123456789
https://facebook.com/someusername

I need:

123456789
someusername

using this regular expression:

(?<=(https?://(www.)?facebook.com/(profile.php?id=)?))([^/#?]+)

I get:

profile.php
someusername

Whats wrong?

like image 718
max ins Avatar asked May 07 '13 08:05

max ins


2 Answers

I advise you to use the System.Uri class to get this information. It does the difficult work for you and can handle all sorts of edge cases.

var profileUri = new Uri(@"http://www.facebook.com/profile.php?id=123456789");
var usernameUri = new Uri(@"https://facebook.com/someusername");

Console.Out.WriteLine(profileUri.Query); // prints "?id=123456789"
Console.Out.WriteLine(usernameUri.AbsolutePath); // prints "/someusername"
like image 62
Rik Avatar answered Oct 03 '22 16:10

Rik


I agree with others on using System.Uri but your regex needs two modifications to work:

  • \ in (profile.php\?id=)
  • (\n|$) at the end

    (?<=(https?://(www\.)?facebook\.com/(profile\.php\?id=)?))([^/#?]+)(\n|$)

like image 40
nima Avatar answered Oct 03 '22 17:10

nima