2

I can't figure out how to match a pattern between LAST / and the end of the line.

I have tons of:
/usr/etc/blabla:/etc/bbb
/usr/etc/blabla:/etc/bffb.gh
/usr/etc/blabla:/local/fffusr
/usr/etc/blabla:/bin/dfusrd
/usr/etc/var:/etc/aaaaaf.ju

For example i want to match "usr" only when it is in the bold part.
I'm using grep.

EDIT:
I've a small problem with this solution:
/([^/]+)$
It doesn't match the pattern if it is immediately after the /, for example those:
/usr/etc/blabla:/bin/usrlala
/bin/bla/:/etc/usr
are not matched

FOUND IT: /([^/]*)$

2

5 Answers 5

2

It would be:

/([^/]+)$

But maybe you must escape the slash (/) depending on your language:

/\/([^\/]+)$/
0
1

Why do you want to use regex on such simple task?

If you're using php you can use

$pos = strrpos($line, '/'); 

to determine last occurance of / and then copy everything from there

$name = substr($line, $pos+1);

regex is not ultimate solution to everything. It will be slower on such simple string operations. Well, it will always be slower to your own procedure parsing a string (if it's written good).

3
  • +1: I'd do it this way in zsh: for line in $(cat input.txt); echo ${line:t}. Regular expression are not the be all and end all.
    – johnsyweb
    Apr 14, 2011 at 11:48
  • i need it to do a grep in a large amount of text file
    – simplex
    Apr 14, 2011 at 13:06
  • So it's even more of a reason NOT to use regex. Just loop through all lines.
    – Kaminari
    Apr 14, 2011 at 17:19
1
echo "
/usr/etc/blabla:/etc/bbb
/usr/etc/blabla:/etc/bffb.gh
/usr/etc/blabla:/local/fffusr
/usr/etc/blabla:/bin/dfusrd
/usr/etc/var:/etc/aaaaaf.ju" | sed -n 's#.*/##;/.*usr.*/p'
fffusr
dfusrd
2
  • i thought the same, but i have tons of file and this solution is really slower compared to a regex search, thanks anyway
    – simplex
    Apr 14, 2011 at 13:07
  • What do you mean by regex-search? sed does regex-search. Which tool(s) do you have? Today, every language has regex. I simplified it a bit - now it just uses sed, not grep. Apr 14, 2011 at 13:38
0

answer in javascript

var s = "/usr/etc/var:/etc/aaaaaf.ju"
s ; //# => /usr/etc/var:/etc/aaaaaf.ju
var last = s.match(/[^/]+$/);
last ; //# => aaaaaf.ju
0

Using PCRE:

$re = '/.+\/.*usr.*/i';

$string = '/usr/etc/blabla:/etc/bbb
/usr/etc/blabla:/etc/bffb.gh
/usr/etc/blabla:/local/fffusr
/usr/etc/blabla:/bin/dfusrd
/usr/etc/var:/etc/aaaaaf.ju';

$nMatches = preg_match_all($re, $string, $aMatches);

Result:

Array
(
    [0] => Array
        (
            [0] => /usr/etc/blabla:/local/fffusr
            [1] => /usr/etc/blabla:/bin/dfusrd
        )

)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.