How to extract contents in square brackets in ruby

I am trying to extract contents inside square brackets. So far I have used 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"
+4
source share
2 answers

Nearly.

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

The first is based on extracting a group instead of a full match; the second one uses lookahead and lookbehind to avoid dividers in the final match.

+7
source

You can do this with regex using Regexp#=~.

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

inside_brackets
  => "cool awesome"

This way you assign a inside_bracketsstring that matches the regular expression, if any, which I think is more readable.

. , .

+2

Source: https://habr.com/ru/post/1692442/


All Articles