regex question

J

Joe Van Dyk

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...
 
L

Logan Capaldo

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
 
A

Assaph Mehr

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
 
J

Joel VanderWerf

Joe said:
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.
 
E

ES

Joe said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,460
Latest member
eibafima

Latest Threads

Top