简体   繁体   中英

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

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.

ie the return string should be folder4/

In php:

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

In perl:

$str = "/folder1/folder2/folder3/folder4/";
$str =~ s#^.*/([^/]+/[^/]*)$#$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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM