Trying to use regular expressions in ruby ​​to search for specific characters

I am trying to use regular expressions in ruby ​​on a rails application to search on a given string and search for any instances of opening and closing square brackets (ie [and]) and select the contents between them.

For instance:

Lorem ipsum [dolor sit] amet...

On this line, the result will be: [dolor sit]

I played with the ruble a bit and found that it more or less does what I want

/\[.*?\]/

So my question is: how do I match everything in square brackets without choosing the brackets themselves? And also how can I integrate them into a ruby ​​script?

Regular expressions are a whole new foundation for me, so any help you guys can offer will be greatly appreciated :)

+3
source share
3

- String # scan

>> s="Lorem ipsum [dolor sit] [amet] ..."
=> "Lorem ipsum [dolor sit] [amet] ..."
>> s.scan(/\[([^\]]*)\]/).flatten
=> ["dolor sit", "amet"]
+4

String#scan:

"Hi [there] how are [you]?".scan(/\[.*?\]/)
 => ["[there]", "[you]"] 

, .

+2

You can wrap the part of Regex that matches the part of the input you want to extract inside ():

str = "Lorem ipsum [dolor sit] amet....".match(/\[(.*?)\]/)
# str --> #<MatchData "[dolor sit]" 1:"dolor sit"> 
str[1] # Will give you 'dolor sit'

Note that you can also access the result of matching by a global variable: $1(usually $iwhere irepresents the index of the matching word).

+1
source

All Articles