Regex problem with gsub

Hi,

i have a dir like that and need the
first part of the first filename =

J:\test>dir /B
20070921_0001.xml
20070921_0002.xml
20070921_0003.xml

i tried with =

str=File.basename(Dir[“J:/test/*.xml”].sort[0]).gsub(/(\w{8}).+/, $1)

but =
TypeError: can’t convert nil into String
from (irb):4:in `gsub’
from (irb):4
from :0

if i use =
irb(main):005:0> str=File.basename(Dir[“J:/test/*.xml”].sort[0])
=> “20070921_0001.xml”
i get the filename

how to change my gsub part to make it work, i want
the first part of the filename, i.e.
filename “20070921_0001.xml”
i want “20070921”

Regards, Gilbert

Gilbert R. wrote:

str=File.basename(Dir[“J:/test/*.xml”].sort[0]).gsub(/(\w{8}).+/, $1)

At this point $1 is nil, which is why you get the error. You have to
keep in
mind that arguments are evaluated before the method is called and $1
will
only have value after that. You need to use ‘\1’ instead of $1.

HTH,
Sebastian

Hi,

Sebastian H. wrote:

Gilbert R. wrote:

str=File.basename(Dir[“J:/test/*.xml”].sort[0]).gsub(/(\w{8}).+/, $1)

At this point $1 is nil, which is why you get the error. You have to keep in
mind that arguments are evaluated before the method is called and $1 will
only have value after that. You need to use ‘\1’ instead of $1.

Thanks!!
Works now. I’m still not sure, when to use \1 and when to use $1

Regards, Gilbert

Hi Gilbert:

The problem it’s not the regex, it’s the second parameter, try instead:

string.gsub(/(\w{7}).+/, ‘\1’)

This supposing you want ever the first seven chars, if you want the
characters before because they can be variable, try this regex:

string.gsub(/(\w*)(_.)…+/, ‘\1’)

I’m not mastered the regular expressions, any corrections appreciated.

Regards,

Jovino

-----Mensaje original-----
De: Gilbert R. [mailto:[email protected]]
Enviado el: sábado, 22 de septiembre de 2007 11:55
Para: ruby-talk ML
Asunto: regex problem with gsub

Hi,

i have a dir like that and need the
first part of the first filename =

J:\test>dir /B
20070921_0001.xml
20070921_0002.xml
20070921_0003.xml

i tried with =

str=File.basename(Dir[“J:/test/*.xml”].sort[0]).gsub(/(\w{8}).+/, $1)

but =
TypeError: can’t convert nil into String
from (irb):4:in `gsub’
from (irb):4
from :0

if i use =
irb(main):005:0> str=File.basename(Dir[“J:/test/*.xml”].sort[0])
=> “20070921_0001.xml”
i get the filename

how to change my gsub part to make it work, i want
the first part of the filename, i.e.
filename “20070921_0001.xml”
i want “20070921”

Regards, Gilbert

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