Mrunal Pradeep Patekar
Mrunal Pradeep Patekar

Reputation: 157

How to extract content within square brackets in ruby

I am trying to extract the content inside the square brackets. So far I have been using this, which works but I was wondering instead of using this delete function, if I could directly use something in regex.

a = "This is such a great day [cool awesome]" 
a[/\[.*?\]/].delete('[]') #=> "cool awesome"

Upvotes: 6

Views: 3473

Answers (2)

You can do this with Regular expression using Regexp#=~.

/\[(?<inside_brackets>.+)\]/ =~ a 
  => 25

inside_brackets
  => "cool awesome"

This way you assign inside_brackets to the string which matches the regular expression if any, which I think it is more readable.

Note: Be careful to place the regular expression at the left hand side.

Upvotes: 2

Amadan
Amadan

Reputation: 198314

Almost.

a = "This is such a great day [cool awesome]"
a[/\[(.*?)\]/, 1]
# => "cool awesome"
a[/(?<=\[).*?(?=\])/]
# => "cool awesome"

The first one relies on extracting a group instead of a full match; the second one leverages lookahead and lookbehind to avoid the delimiters in the final match.

Upvotes: 11

Related Questions