0

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 ""

1 Answer 1

5

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

""[/abc/]

For the example given:

"abc123def"[/(?<=abc)[0-9]*/]
#⇒ "123"
Sign up to request clarification or add additional context in comments.

5 Comments

String#[] is always presumed to be for things like substrings but it's also quite flexible.
Apologies for not being clear. But:"abc123def"[/abc([0-9]*)/] => "abc123" "abc123def".match(/abc([0-9]*)/)[1] => "123"
Please see a comment: you are using a wrong regexp there.
Thank you very much
@MarkKang you can also pass the index of a capture group as the second argument to String#[], e.g: "abc123def"[/abc([0-9]*)/, 1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.