Mark Kang
Mark Kang

Reputation: 191

Accessing an array element or return an empty string

When the following regular expression match yields no matching captures, accessing the element [1] will return the following error:

"".match(/(abc)/)[1] 

returns the following error:

NoMethodError: undefined method `[]' for nil:NilClass

Is there a more concise single line implementation to perform the equivalent?

result = "".match(/(abc)/).nil? ? "" : "".match(/(abc)/)[1] 

I am looking for a solution that does not require having to repeat the matching code **"".match(/abc/)** and yet safely access the first captured group or fail with an empty string as result.

[edited to be clearer]

For the following string, the match will be "123":

"abc123def".match(/abc([0-9]*)/)[1] => "123"

and "abcdef" should return ""

Upvotes: 0

Views: 53

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

Yes, it is String#[] with regular expression as an argument.

""[/abc/]

For the example given:

"abc123def"[/(?<=abc)[0-9]*/]
#⇒ "123"

Upvotes: 5

Related Questions