kambi
kambi

Reputation: 3423

Capturing optional parameter in ruby

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

Answers (2)

Rana Pratap Singh
Rana Pratap Singh

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.

1st URL ). https://thumbor-cdn1.abc.com/unsafe/700x0/filters:quality(90)/https://s3.amazonaws.com/abc/app_photos/images/1528/original/cover_daily-1.jpg

2nd URL ). https://thumbor-cdn1.abc.com/unsafe/600x0/https://s3.amazonaws.com/abc/users/images/000/263/588/blurred_preview/263588-profile-image-HYU0HBxA5c.jpg

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

Rohit Jain
Rohit Jain

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:

  • One capturing the X part.
  • Another capturing the Y part.

So, you will receive an array with these two groups only. And hence you won't get the or part.

Upvotes: 3

Related Questions