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"
Square brackets indicate character classes in Ruby regular expressions.
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.
=~ 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With