A smart way

hello,

I’m new and I’m searching for an smart way to extract
the string ‘daniel’ from this line

···


I can find this line via: line =~ /<file( +)name( *)=( *"(.+)")( *)>/
But how to extrace this sting?

This question is only an example for much similar things
(I’m not searching for XML-Stuff).

daniel

Hi –

hello,

I’m new and I’m searching for an smart way to extract
the string ‘daniel’ from this line

--

I can find this line via: line =~ /<file( +)name( *)=( *“(.+)”)( *)>/
But how to extrace this sting?

You can generate a MatchData object, and then address that object
with numerical indices. Index 0 will be the whole match; index 1
will be the first () submatch, etc.

str = ‘’
m = /<file +name *= *“(.+)” *>/.match(str)
puts “Whole match is: #{m[0]}”
puts “First submatch is: #{m[1]}”

(You can also use the special variable $1 to get at the first
submatch.)

David

···

On Sun, 12 Jan 2003, daniel wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

Hi Daniel,

The brackets () in a regular expression cause Ruby to “remember” the
matches. The first match is stored in $1, the second in $2 and so on.

line = ‘’
line =~ /file( +)name( *)=( *“(.+)”)( *)/
^ ^ ^ ^ ^
$1 $2 $3 $4 $5

In this case, you are interested in $4

Example:

$ irb --simple-prompt

line = ‘’
line =~ /file( +)name( *)=( *“(.+)”)( *)/
$4
“daniel”

Cheers,
Daniel Carrera
Graduate Teaching Assistant. Math Dept.
University of Maryland. (301) 405-5137

How about this?

···

C:>irb
irb(main):001:0> line = ‘’
“<file name="daniel">”
irb(main):002:0> line =~ /<file +name *= *“(.+)” *>/
0
irb(main):003:0> puts $1
daniel
nil
irb(main):004:0> exit

C:>ruby -v
ruby 1.7.3 (2002-11-17) [i386-mswin32]

I took the liberty of removing the unwanted parenthesis from your regex.
I am assuming that you are new to Ruby and not to regex handling.
If not, let me know and will try and elaborate more …

HTH,
– shanko

“daniel” daniel.daniel@aon.at wrote in message
news:3e20bc01$0$37624$91cee783@newsreader01.highway.telekom.at…

hello,

I’m new and I’m searching for an smart way to extract
the string ‘daniel’ from this line

--

I can find this line via: line =~ /<file( +)name( *)=( *“(.+)”)( *)>/
But how to extrace this sting?

This question is only an example for much similar things
(I’m not searching for XML-Stuff).

daniel

Daniel Carrera dcarrera@math.umd.edu schrieb in im Newsbeitrag:
Pine.GSO.4.44.0301112014240.757-100000@demoivre.math.umd.edu…

Hi Daniel,

The brackets () in a regular expression cause Ruby to “remember” the
matches. The first match is stored in $1, the second in $2 and so on.

[…]

This works fine :wink:

thx, daniel