Re: Backreferences in case statements



On 03.05.2008 18:00, loveajax@xxxxxxxxx wrote:

I am not sure if this is possible. I have a case statement which
checks for a regular expression. For example:

case text
when /(abc)(.)*/
when /(xyz)(.)*/
end

In the above snippet how can I use the instance variables pre_match
and post_match? I tried calling these methods without any qualifiers
but I got a NoMethodError. Where does Ruby store the MatchData if the
matching is done in a case statement?

$ irb
irb(main):001:0> /b/ =~ "abc"
=> 1
irb(main):002:0> $`
=> "a"
irb(main):003:0> $'
=> "c"
irb(main):004:0> $~
=> #<MatchData:0x7ff9eb54>
irb(main):005:0> $~.to_a
=> ["b"]
irb(main):006:0> $~.pre_match
=> "a"
irb(main):007:0> $~.post_match
=> "c"
irb(main):008:0>

But why do you have groups in your regular expressions if you are not interested in the content? Also "(.)*" seems a bit odd because it might not yield what you expect:

irb(main):008:0> /a(.)*/ =~ "abcdef"
=> 0
irb(main):009:0> $1
=> "f"

IMHO it is generally a bad idea to use grouping in the way you do it because it will capture a lot that you are not interested in. It seems you might rather want "(.*)".

Kind regards

robert
.



Relevant Pages

  • Re: RegularExpressionValidator?
    ... > I have this snippet: ... > My question is why this regular expression is not invoked if I leave the ... > textbox blank? ... function properly (if not with a little extra maintenance on your part). ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: Regexp to match an URL in an HTML <a href=""></a> tag
    ... > I am trying to craft a regular expression to filter an URL from a <a ... > I use the regular expression from this snippet of code: ...
    (comp.lang.perl)
  • Re: Regexp to match an URL in an HTML <a href=""></a> tag
    ... > I am trying to craft a regular expression to filter an URL from a ... > the regular expression from this snippet of code: ...
    (comp.lang.perl)
  • Regexp to match an URL in an HTML <a href=""></a> tag
    ... I am trying to craft a regular expression to filter an URL from a <a ... I use the regular expression from this snippet of code: ... foreach my $message ... Charles ...
    (comp.lang.perl)
  • Re: Regular Expression Hangs
    ... You wouldn't need a regular expression to ... a single fixed string. ... Those patterns are defined by rules that are expressed in the ... will capture the following: ...
    (microsoft.public.dotnet.languages.csharp)