[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

regex question

Joe Van Dyk

3/17/2005 4:46:00 AM

I have a lot of code that looks like this:

line = "some line of stuff"
line =~ /regex stuff here/
if $1; result = $1; end

Generally, I'm checking to see if a given regex exists in a string and
I usually want to save some stuff from it.

But my way seems kinda clunky...


5 Answers

Logan Capaldo

3/17/2005 5:05:00 AM

0

On Thu, 17 Mar 2005 13:46:24 +0900, Joe Van Dyk <joevandyk@gmail.com> wrote:
> I have a lot of code that looks like this:
>
> line = "some line of stuff"
> line =~ /regex stuff here/
> if $1; result = $1; end
>
> Generally, I'm checking to see if a given regex exists in a string and
> I usually want to save some stuff from it.
>
> But my way seems kinda clunky...
>
>
match_data = line.match(/regular expression/)
unless match_data[1].nil?
result = match_data[1]
end

match_data[0] is $&
match_data[1] is $1
etc.
The other advantage being is that you can keep the MatchData object
around after you perform another match, since $1, $2, etc.. will get
over-written


Assaph Mehr

3/17/2005 5:07:00 AM

0


> line = "some line of stuff"
> line =~ /regex stuff here/
> if $1; result = $1; end
>
> Generally, I'm checking to see if a given regex exists in a string
and
> I usually want to save some stuff from it.
>
> But my way seems kinda clunky...

I like this way:

.. if md = line.match(regex) # assign expr result in if
.. puts md.captures
.. end

HTH,
Assaph

Joel VanderWerf

3/17/2005 5:08:00 AM

0

Joe Van Dyk wrote:
> I have a lot of code that looks like this:
>
> line = "some line of stuff"
> line =~ /regex stuff here/
> if $1; result = $1; end
>
> Generally, I'm checking to see if a given regex exists in a string and
> I usually want to save some stuff from it.

"foo bar"[/foo/]
=> "foo"

works nice for this.

Also:

"foo bar"[/\w+ (\w+)/, 1]
=> "bar"

Also, String#scan, if you don't know how many matches to look for.


ES

3/17/2005 5:09:00 AM

0

Joe Van Dyk wrote:
> I have a lot of code that looks like this:
>
> line = "some line of stuff"
> line =~ /regex stuff here/
> if $1; result = $1; end
>
> Generally, I'm checking to see if a given regex exists in a string and
> I usually want to save some stuff from it.
>
> But my way seems kinda clunky...

You could use String#scan.

E



Assaph Mehr

3/17/2005 5:10:00 AM

0


> match_data = line.match(/regular expression/)
> unless match_data[1].nil?

careful, match_data can be nil itself if there was no match.