Rails - extract substring with in [ and ] from string

Viewed 180

This works.

"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"

But I want to extract substring within [ and ].

input:

string = "123 [asd]"

output:

asd

Anyone can help me?

2 Answers

Here are a few more ways to extract the desired string.

str = "123 [asd] 456"

#1

r = /
    (?<=\[)  # match '[' in a positive lookbehind
    [^\]]*   # match 1+ characters other than ']'
    (?=\])   # match ']' in a positive lookahead
    /x       # free-spacing regex definition mode

str[r]
  #=> "asd"

#2

r = /
    \[       # match '['
    [^\]]*   # match 1+ characters other than ']'
    \]       # match ']'
    /x       # free-spacing regex definition mode

str[r][1..-2]
  #=> "asd"

#3

r = /
    .*\[     # match 0+ characters other than a newline, then '['
    |        # or
    \].*     # match ']' then 0+ characters other than a newline
    /x       # free-spacing regex definition mode

str.gsub(r, '')
  #=> "asd"

#4

n = str.index('[')
  #=> 4
m = str.index(']', n+1)
  #=> 8
str[n+1..m-1]
  #=> "asd"

See String#index.

Related