0

Here is the code

string = "Looking for the ^[cows]"
footnote = string[/\^\[(.*?)\]/]

I was hoping that footnote would equal cows

What I get is footnote equals ^[cows]

Any help?

Thanks!

1
  • footnote is equal to ^[cows], because that's what you are explicitly asking for in the pattern \^\[(.*?)\]. The cows substring resides in the especial variable $1 (group one). Be aware that string[regexp] will return the match of the entire pattern, not the groups. Commented Mar 26, 2015 at 18:28

4 Answers 4

4

You can specify which capture group you want with a second argument to []:

string = "Looking for the ^[cows]"
footnote = string[/\^\[(.*?)\]/, 1]
# footnote == "cows"
Sign up to request clarification or add additional context in comments.

1 Comment

.match() might be a better solution in some cases, but this works best for me.
0

According to the String documentation, the #[] method takes a second parameter, an integer, which determines the matching group returned:

a = "hello there"

a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil

You should use footnote = string[/\^\[(.*?)\]/, 1]

Comments

0

If you want to capture subgroups, you can use Regexp#match:

r = /\^\[(.*?)\]/
r.match(string) # => #<MatchData "^[cows]" 1:"cows">
r.match(string)[0] # => "^[cows]"
r.match(string)[1] # => "cows"

Comments

0

An alternative to using a capture group, and then retrieving it's contents, is to match only what you want. Here are three ways of doing that.

#1 Use a positive lookbehind and a positive lookahead

string[/(?<=\[).*?(?=\])/]
  #=> "cows"  

#2 Use match but forget (\K) and a positive lookahead

string[/\[\K.*?(?=\])/]
  #=> "cows"  

#3 Use String#gsub

string.gsub(/.*?\[|\].*/,'')
  #=> "cows"  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.