Reputation: 125
I try to find a regex in order to extract the name of a file. My String is path/string.mystring
for exemple
totot/tototo/tatata.tititi/./com.myString
I try to get myString
.
I tried String[] test = foo.split("[*.//./.]");
Upvotes: 0
Views: 96
Reputation: 1220
Try this code:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Regexp
{
public static void main(String args[])
{
String x = "totot/tototo/tatata.tititi/./com.myString";
Pattern pattern = Pattern.compile( "[a-z0-9A-Z]+$");
Matcher matcher = pattern.matcher(x);
while (matcher.find())
{
System.out.format("Text found in x: => \"%s\"\n",
matcher.group(0));
}
}
}
Upvotes: 0
Reputation: 20254
A similar question has been answered here. I would say that using a regex to get the file name is the wrong way to go (for example, if your code ever tries to run against a Windows file path the slashes in your regex will be the wrong way round) - why not just use:
new File(fileName).getName();
to get the name of the file, and then extract the part of the file name that you want using a simpler split:
String[] fileNameParts = foo.split("\\.");
String partThatYouWant = fileNameParts [fileNameParts.length - 1];
Upvotes: 1
Reputation: 7226
Maybe you should just use the String API. Something like this:
public static void main(String[] args){
String path = "totot/tototo/tatata.tititi/./com.myString";
System.out.println(path.substring(path.lastIndexOf(".") + 1));
}
Does it fit your case? There are many problems in working with indexes. But if you're always sure there will be a .
you can use this without any problems.
Upvotes: 0
Reputation: 46408
A non-regex solution using String#subString
& String#lastIndexOf
would be.
String path="totot/tototo/tatata.tititi/./com.myString";
String name = path.substring(path.lastIndexOf(".")+1);
Upvotes: 0
Reputation: 195059
My String is path/string.mystring
If your string pattern is fixed following the rule above, how about:
string.replaceAll(".*\\.","")
Upvotes: 0
Reputation: 234795
If you want to split on period or slash, the regex should be
foo.split("[/\\.]")
Alternatively, you could do this:
String name = foo.substring(foo.lastIndexOf('.') + 1);
Upvotes: 0