Reputation: 617
I have an input field where the user can post a link to a facebook page. Right now I am using regex to validate the URL.
URL_regex = /\A(http|https|ftp):\/\/([\w]*)\.([\w]*)\.(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)(\.[a-z]{1,3})?/i
I only want the following four versions to pass the validation:
https://www.facebook.com/redbull
http://www.facebook.com/redbull
www.facebook.com/redbull
facebook.com/redbull
Then I want to only want to store the "redbull" part in the database. I tried Rubular but I can't figure out the logic of the regex.
Thanks in advance
Found a solution, thx to caley:
URL_regex = /\A((http|https):\/\/)?(www\.)?facebook\.com\/([\S]+)/i
Upvotes: 1
Views: 134
Reputation: 21
You're almost there. You just need to add another capture group.
\A(http|https|ftp):\/\/([\w]*)\.([\w]*)\.(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)\/(\w+)?
or
(http|https:ftp:\/\/)?\w*.\w+.(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)\/(\w+)
irb(main):014:0> if x =~ /\A(http|https|ftp):\/\/([\w]*)\.([\w]*)\.(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)\/(\w+)?/
irb(main):015:1> puts $5
irb(main):016:1> end
redbull
=> nil
Upvotes: 0
Reputation: 66837
You already got nice answers for regular expressions, but I wanted to point out the URI
module:
>> require 'uri'
#=> true
>> uri = URI.parse "https://www.facebook.com/redbull"
#=> #<URI::HTTPS:0x000001010a41a8 URL:https://www.facebook.com/redbull>
>> uri.scheme
#=> "https"
>> uri.host
#=> "www.facebook.com"
>> uri.path
#=> "/redbull"
Maybe validating the individual parts is easier than one big regex.
Upvotes: 1
Reputation: 3887
This will match only the 4 variants you suggested, plus http://facebook.com/redbull
and https://facebook.com/redbull
as these may also be common variants.
/\A((http|https):\/\/)?(www\.)?facebook\.com\/(\w*)?/i
Upvotes: 1
Reputation: 87073
Without RegEx you can use it:
var your_url = ''; //here, you place your URL
console.log(your_url.slice(your_url.lastIndexOf('/') + 1));
This will give desired output.
Upvotes: 0