Reputation: 53896
To truncate a String here is what I'm using :
String test1 = "this is test truncation 1.pdf";
String p1 = test1.substring(0, 10) + "...";
System.out.println(p1);
The output is 'this is te...' How can I access the file name extension so that output becomes : 'this is te... pdf' I could use substring method to access the last three characters but other file extensions could be 4 chars in length such as .aspx
Is there a regular expression I can use so that "this is test truncation 1.pdf" becomes "this is te... pdf"
Upvotes: 8
Views: 13188
Reputation: 159844
You could simply use
test1.substring(0, 10) + "..." + test1.substring(test1.lastIndexOf('.'))
Upvotes: 3
Reputation: 41230
try this -
String test1 = "this is test truncation 1.pdf";
String[] test2 = test1.split("\\.");
String p1 = test1.substring(0, 10) + "..." + test2[test2.length-1];
System.out.println(p1);
Upvotes: 0
Reputation: 12252
I use this approach but it will work only if u have single "." and that one too for file name extension.May be this one is a novice approach as u can use split method of String class too.......
String str="abcdefg ghi.pdf";
int dotIndex=str.indexOf(".")+1;
if(str.indexOf(" ", dotIndex)!=-1)
System.out.println(str.substring(dotIndex,str.indexOf(" ", dotIndex) ));
else
{
System.out.println(str.substring(dotIndex,str.length() ));
}
Upvotes: 0
Reputation: 6322
You can do it all with a quick regex replace like this:
test1.replaceAll("(.{0,10}).*(\\..+)","$1...$2")
Upvotes: 8
Reputation: 5256
Do it like this :
String[] parts = test1.split("\\.");
String ext = parts[parts.length-1];
String p1 = test1.substring(0, 10) + "..."+ext;
System.out.println(p1);
Upvotes: 2
Reputation: 425
You could use .+[.](.*?)
This matches all characters including dots, then a dot, then any character, but not greedy, so the first part should grab all of the string preceding the last dot. The capturing group will allow you to retrieve the part you need.
Upvotes: 0
Reputation: 19856
For this simple task you don't need Regex
String p1 = test1.substring(0, 10) + "..." + test1.substring(test1.lastIndexof('.'));
Upvotes: 0