Reputation: 1481
Issue: I need my regex to have an optional group. Specifically "www" and "(https|http):.
Regex:
/\A^(https|http):\/\/www\.twitter\.com\/\w+\/status\/\d+/
Validation (FYI)
validates :twitter_link, format: { with: /\A^(https|http):\/\/www\.twitter\.com\/\w+\/status\/\d+/}
I need to make the "www" optional. Everything else seems to be working good.
What I need (and in order):
Might or might not start with "http:" or "https:".
Must include: "twitter.com/".
Must include: Any letter/number/character after "twitter.com/".
Must include: "status" after the twitter #{twitter_user_name_} like "/gem/status".
Must include: Only numbers after "status/"
Such as these possible links:
Possible Links:
urls = [
"https://twitter.com/Twitt_erDev/status/850006245121695744",
"http://twitter.com/Twit1243terDev/status/850006245121695744",
"https://www.twitter.com/Twi234_tterDev/status/850006245121695744",
"http://www.twitter.com/TwitterDev/status/850006245121695744",
"http://m.twitter.com/Tw11itterDev/status/850006245121695744",
"https://m.twitter.com/Tw11itterDev/status/850006245121695744",
"www.twitter.com/Twitt11erDev/status/850006245121695744",
"m.twitter.com/Tw11itterDev/status/850006245121695744",
"twitter.com/Twitte345_rDev/status/850006245121695744",
]
How to make the "www" and "http/https" optional? And is my regex secure/good?
Upvotes: 0
Views: 63
Reputation: 19641
To make something optional, you should use the ?
quantifier, which basically means zero or one times.1 Now, if what you want to make optional is more than one character, you simply put it in a group (preferably, a non-capturing group) and then follow it with the question-mark-quantifier.
Something like the following should work for all your examples:
^(?:https?:\/\/)?(?:(?:www|m)\.)?twitter\.com\/\w+\/status\/\d+
1 Another optional quantifier is the *
, which means between zero and unlimitted times but it's not the right fit for your case.
Upvotes: 1