Link to home
Start Free TrialLog in
Avatar of PHIL Sawyer
PHIL SawyerFlag for United Kingdom of Great Britain and Northern Ireland

asked on

finding text after /

Want to extract last part of string following last forward slash

eg
Have a txt file with say the following
/fahah/rjyjke/23454/test.rpt
/agddddddddd/ff/ff/ff/ff/ff/ff/fred.rpt
/a/test4.rpt
etc etc
I want to return ..
test.rpt
fred.rpt
test4.rpt

Regards
Avatar of farzanj
farzanj
Flag of Canada image

Try:

line = "/fahah/rjyjke/23454/test.rpt"
re = /.*\/([^/]+)$/

match1 = line.match re

Open in new window

Avatar of PHIL Sawyer

ASKER

Ruby does not like this - it throws error
syntax error, unexpected ')'
re = /.*\/([^]/+)$/

Regards
ln = "/fahah/rjyjke/23454/test.rpt"
regex = /.*\/([^\/]+)$/
puts ln.gsub(regex, '\1')
hi Phil,
there is a little typo in farzanj's post
the / inside the [] needs escaping
SOLUTION
Avatar of farzanj
farzanj
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK - Yes I saw the typo and changed my logic to ..

 list.each do |z|
       z=z.scan(/.*\/([^\/]+)$/)
       puts z
  end

Thanks Guys

Hi Gertone
@Gertone

That typo is not in my post.  It is in Author's post.
and the line.match re will return the whole match, including the part matched by .*\/
what you would need to do then is this

puts line.match(re)[1]
Gertone
Is "puts ln.gsub(regex, '\1') " bringing back last match - is that what  the '\1' is doing?

Phil
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Gertone:

See my second post. I never used Ruby.  I do regex only.
Is "puts ln.gsub(regex, '\1') " bringing back last match - is that what  the '\1' is doing?

it is substituting the line with the part that is in the first pair of brackets
there is only one pair of brackets, so it is returning that

ln.match(regex)[1] is returning the same
ln.match regex
equals
ln.match(regex)[0], returns the whole match
Gertone
Just missed you post earlier which explains my last post

Phil
Thanks