需要正则表达式显示字符
的第二个出现的字符串示例:“/ folder1 / folder2 / folder3 / folder4 /”
在这种情况下,如果我要求第二次出现斜杠(/),它会出现在folder4之前,我希望从最后一次出现的第二个字符开始返回子字符串。
,即返回字符串应为 folder4 /
答案 0 :(得分:2)
在php中:
$str = "/folder1/folder2/folder3/folder4/";
$str = preg_replace('#^.*/([^/]+/[^/]*)$#', "$1", $str);
在perl:
$str = "/folder1/folder2/folder3/folder4/";
$str =~ s#^.*/([^/]+/[^/]*)$#$1#;
答案 1 :(得分:1)
- 1
作为第二个lastIndexOf()
substring()
像这样:
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);
或者更具可读性
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);
答案 2 :(得分:0)
:
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);
其中2出现。这允许您将所有内容分组,以便您也可以处理其他组。