Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Extract TwitterUsername from URL

Tags:

regex

twitter

I'm looking for an universal regular expression which extracts the twitter username from an url.

Sample URLS

http://www.twitter.com/#!/donttrythis

http://twitter.com/KimKardashian

http://www.twitter.com/#!/KourtneyKardash/following

http://twitter.com/#!/jasonterry31/lists/memberships

like image 408
n00b Avatar asked May 10 '11 09:05

n00b


2 Answers

There are a couple more test cases to make a universal regexp.

  • https URLs are also valid
  • URLs like twitter.com/@username also go to username's profile

This should do the trick in PHP

preg_match("|https?://(www\.)?twitter\.com/(#!/)?@?([^/]*)|", $twitterUrl, $matches);

If preg_match returns 1 (a match) then the result is on $matches[3]

like image 187
Lombo Avatar answered Sep 30 '22 12:09

Lombo


Try this:

^https?://(www\.)?twitter\.com/(#!/)?(?<name>[^/]+)(/\w+)*$

The sub group "name" will contain the twitter username.
This regex assumes that each URL is on its own line.


To use it in JS, use this:

^https?://(www\.)?twitter\.com/(#!/)?([^/]+)(/\w+)*$

The result is in the sub group $3.

like image 43
Daniel Hilgarth Avatar answered Sep 30 '22 14:09

Daniel Hilgarth