crowhill
crowhill

Reputation: 2548

ruby and regex grouping

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!

Upvotes: 0

Views: 97

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110675

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"  

Upvotes: 0

user229044
user229044

Reputation: 239290

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"

Upvotes: 0

Shawn Bush
Shawn Bush

Reputation: 642

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]

Upvotes: 0

Andrew Larson
Andrew Larson

Reputation: 483

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

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

Upvotes: 4

Related Questions