Reputation: 3423
I want to catch a mandatory and an optional parameter.
lets say I have a string
"X or Y"
and "or Y" is optional.
I can do
scan /(.*) (or (.*))?/
and receive an array with size 3 that includes also the result for the optional catch.
How can I write the scan to receive an array for only the 2 X and Y possibillities?
Thank You
Upvotes: 2
Views: 702
Reputation: 867
I needed same answer for this scenario, I googled a lot to get better solution, after playing with logic finally I got success. And it is working perfectly fine in every scenario. Whether URL have one parameter or two. Even we can expand it in n parameters. Very easy to do.
My problem statement was, I had two URLs with small difference.
You can see that 1st URL have 700x0/filters:quality(90)
and 2nd URL have only one parameter 600x0
And regex is - (http|https):\/\/thumbor-cdn1.abc.com\/unsafe\/((.*?)|\/(.*?))\/(http|https):\/\/s3.amazonaws.com\/(abc|xyz)
Above url are used for example purpose, for your case you can use valid url. Thank you!
Upvotes: 0
Reputation: 213253
You can make the outer group of the 2nd part as non-capturing
group:
/(.*) (?:or (.*))?/
Now you have only two capturing groups in your regex:
X
part.Y
part.So, you will receive an array with these two groups only. And hence you won't get the or
part.
Upvotes: 3