Robert Andrews
Robert Andrews

Reputation: 1239

regex to match either URL form

I am matching for the username portion in Twitter profile URLs - eg. http://www.twitter.com/joebloggs

Currently, I'm successfully using http://www.twitter.com/(\w+)

But, in some instances, the source URLs are in the format http://www.twitter.com/@joebloggs

This is unnecessary, but I still need to find "joebloggs" all the same. So I need to be matching for either the format without @ or with @.

I have tried various methods using the pipe or vertical bar.

Thanks.

Upvotes: 0

Views: 78

Answers (1)

anubhava
anubhava

Reputation: 785286

You can make @ optional by using:

^http:\/\/www\.twitter\.com\/@?(\w+)

Explanation:

^            # match start of input
http:        # match literal http://
\/\/         # match 2 // (escaping is needed for some regex engines)
www          # match literal www
\.           # match literal dot (escaping since dot is special meta char)
twitter\.com # match literal twitter.com
\/           # match literal /
@?           # match optional @
(\w+)        # match 1 or more word characters and group it

Upvotes: 2

Related Questions