Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract content within square brackets in ruby

Tags:

regex

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"
like image 314
Mrunal Pradeep Patekar Avatar asked Jan 19 '18 22:01

Mrunal Pradeep Patekar


People also ask

What do square brackets mean in Ruby?

Square brackets indicate character classes in Ruby regular expressions.

How do you use square brackets in regex?

Use square brackets ( [] ) to create a matching list that will match on any one of the characters in the list. Virtually all regular expression metacharacters lose their special meaning and are treated as regular characters when used within square brackets.

What does =~ mean in Ruby?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.


2 Answers

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.

like image 179
Amadan Avatar answered Nov 15 '22 02:11

Amadan


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.

like image 43
Ana María Martínez Gómez Avatar answered Nov 15 '22 00:11

Ana María Martínez Gómez