2

Need an Regex to display a string from the second last occurence of a character

Example: "/folder1/folder2/folder3/folder4/"

In this case, if I ask for 2nd occurrence of slash (/) from last , it appears before folder4, and I expect to return substring from 2nd last occurrence of a character.

i.e the return string should be folder4/

Birlla
  • 1,700
  • 2
  • 15
  • 17
  • 2
    [Click for answer](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html). – Maroun Apr 07 '14 at 06:43
  • possible duplicate [how-to-find-nth-occurrence-of-character-in-a-string][1] [1]: http://stackoverflow.com/questions/3976616/how-to-find-nth-occurrence-of-character-in-a-string – yarivt Apr 07 '14 at 06:47

3 Answers3

2

In php:

$str = "/folder1/folder2/folder3/folder4/";
$str = preg_replace('#^.*/([^/]+/[^/]*)$#', "$1", $str);

In perl:

$str = "/folder1/folder2/folder3/folder4/";
$str =~ s#^.*/([^/]+/[^/]*)$#$1#;
Toto
  • 89,455
  • 62
  • 89
  • 125
  • This was very useful, thanks! For the RAW regex, if anybody else is gonna use this, ignore the hashtags - these are php-specific – lucidbrot Aug 24 '16 at 12:40
1
  • Look for the last occurence of your token
  • Take the result - 1 as parameter for a second lastIndexOf()
  • Take this result as param for substring()

Like so:

final String example = "/folder1/folder2/folder3/folder4/";
final String result  = example.substring(example.lastIndexOf('/', example.lastIndexOf('/') - 1), example.length() - 1);

System.out.printf("%s\n", result);

Or a bit more readable

final String example = "/folder1/folder2/folder3/folder4/";
int pos;

pos = example.lastIndexOf('/');
pos = example.lastIndexOf('/', pos - 1);
result = example.substring(pos, example.length - 1);

System.out.println(result);
ifloop
  • 8,079
  • 2
  • 26
  • 35
0

in Java:

    String fileName = "/folder1/folder2/folder3/folder4/";
    ArrayList<String> arr = new ArrayList<>();

    Pattern p = Pattern.compile("(.*?)\/");
    Matcher m = p.matcher(fileName);
    while(m.find())
    {
        arr.add(m.group(1));            
    }       
    return arr.get(arr.size()-2);

where 2 is occurrence. This allows you to have everything grouped so you can handle also other groups.

aprodan
  • 559
  • 5
  • 17