I have a string:
/abc/def/ghfj/ijk/lmn.doc
I would like to extract ghfj from this.
I tried in this manner: str.substring(str.indexOf("/",9),str.indexOf("/"));
Could someone please provide some help?
I have a string:
/abc/def/ghfj/ijk/lmn.doc
I would like to extract ghfj from this.
I tried in this manner: str.substring(str.indexOf("/",9),str.indexOf("/"));
Could someone please provide some help?
Assuming you are trying to find parent location of specified file simplest way would be using File
class or Path
instead of String methods. Your code will be more readable and probably safer.
Using java.io.File
:
String location = "/abc/def/ghfj.doc";
File f = new File(location);
String parentName = f.getParentFile().getName();
System.out.println(parentName);
Using java.nio.file.Path
:
String location = "/abc/def/ghfj.doc";
Path p = Paths.get(location);
String parent = p.getParent().getFileName().toString();
System.out.println(parent);
Output in both cases: def
In case of selecting def
in /abc/def/ghfj/ijk/lmn.doc
you could use Path#getName(N)
where N
is zero-based index of elements from farthermost ancestor to selected file like abc
is 0
, def
is 1
,...
So your code can look like:
String location = "/abc/def/ghfj/ijk/lmn.doc";
Path p = Paths.get(location);
String parent = p.getName(1).getFileName().toString();
System.out.println(parent);// Output: def
Quick and dirty solution using a regular expression and groups:
public class AClass {
private static final String TEXT = "/abc/def/ghfj/ijk/lmn.doc";
private static final String REGULAR_EXPRESSION = "(/[^/]*){2}/([^/]*)/.*";
public static void main(final String[] args) {
final Pattern pattern = Pattern.compile(REGULAR_EXPRESSION);
final Matcher matcher = pattern.matcher(TEXT);
if (matcher.matches()) {
// the following variable holds "ghfj"
String value = matcher.group(2);
System.out.println(value);
}
}
}
Now you need to be more precise in order to allow us to fine tune the regular expression to your concrete needs.
Edit: I edited the solution according to your own edit. The regular expression has to be understood as follows:
(/[^/]*){2}
: two times the character /
followed by any character except /
/
: an additional /
character([^/]*)
: a group of characters not containing /
/.*
: a /
character followed by any other characterThen matcher.group(2)
returns the String held by the group represented by the ([^/]*)
part of the above regular expression.