Re: regex capture and assign... in one line?

From: Nate M. [mailto:[email protected]]

$str = “foo123”;

my ($foo,$bar) = $str =~ /(\w+)(\d+)/;

irb(main):001:0> str = “foo123”
=> “foo123”
irb(main):004:0> _,foo,bar = /(\w+)(\d+)/.match( str ).to_a
=> [“foo123”, “foo12”, “3”]

Perhaps you meant ([a-z]+), but that’s obviously not the point.

Gavin K. wrote:

From: Nate M. [mailto:[email protected]]

$str = “foo123”;

my ($foo,$bar) = $str =~ /(\w+)(\d+)/;

irb(main):001:0> str = “foo123”
=> “foo123”
irb(main):004:0> _,foo,bar = /(\w+)(\d+)/.match( str ).to_a
=> [“foo123”, “foo12”, “3”]

And if you use this a lot, and can include your own mini-library stuff,
make it simpler:

class Regexp
def %( str )
matches = match(str).to_a
matches.shift
matches
end
end

foo, bar = /(\D+)(\d+)/ % “foo123”
p foo, bar
#=> “foo”
#=> “123”

Or if you like it the other way around:
class String
def &( regexp )
matches = regexp.match( self ).to_a
matches.shift
matches
end
end

foo, bar = “foo123” & /(\D+)(\d+)/

I’m not sure if I like ‘%’ better (ala modulo, as in “pare down my
string and give me whatever the regexp leaves”), or ‘&’ better (ala set
intersection, as in “find whatever is common between this string and
regexp”). Up to you to pick from those, or choose another. Non-unary
operator methods left undefined in core Ruby for String and Regexp:

irb(main):002:0> NON_UNARY_OPERATOR_METHODS
=> ["[]", “[]=”, “**”, “~”, “*”, “/”, “%”, “+”, “-”, “>>”, “<<”, “&”,
“^”, “|”, “<=”, “<”, “>”, “>=”, “<=>”, “==”, “===”, “=~”]

irb(main):003:0> NON_UNARY_OPERATOR_METHODS - “”.methods
=> ["**", “~”, “/”, “-”, “>>”, “&”, “^”, “|”]

irb(main):004:0> NON_UNARY_OPERATOR_METHODS - //.methods
=> ["[]", “[]=”, “**”, “*”, “/”, “%”, “+”, “-”, “>>”, “<<”, “&”, “^”,
“|”, “<=”, “<”, “>”, “>=”, “<=>”]

Phrogz wrote:

irb(main):002:0> NON_UNARY_OPERATOR_METHODS
=> ["[]", “[]=”, “**”, “~”, “*”, “/”, “%”, “+”, “-”, “>>”, “<<”, “&”,
“^”, “|”, “<=”, “<”, “>”, “>=”, “<=>”, “==”, “===”, “=~”]

irb(main):003:0> NON_UNARY_OPERATOR_METHODS - “”.methods
=> ["**", “~”, “/”, “-”, “>>”, “&”, “^”, “|”]

irb(main):004:0> NON_UNARY_OPERATOR_METHODS - //.methods
=> ["[]", “[]=”, “**”, “*”, “/”, “%”, “+”, “-”, “>>”, “<<”, “&”, “^”,
“|”, “<=”, “<”, “>”, “>=”, “<=>”]

Er, of course ‘~’ shouldn’t be listed in the above, since it is an
unary operator.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs