Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to truncate a String

Tags:

java

regex

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"

like image 926
blue-sky Avatar asked Dec 20 '12 10:12

blue-sky


People also ask

How do I truncate a string?

Another way to truncate a String is to use the split() method, which uses a regular expression to split the String into pieces. The first element of results will either be our truncated String, or the original String if length was longer than text.

How do you truncate a string in C++?

As Chris Olden mentioned above, using string::substr is a way to truncate a string. However, if you need another way to do that you could simply use string::resize and then add the ellipsis if the string has been truncated. You may wonder what does string::resize ?


2 Answers

You can do it all with a quick regex replace like this:

test1.replaceAll("(.{0,10}).*(\\..+)","$1...$2")
like image 91
Francisco Paulo Avatar answered Oct 28 '22 05:10

Francisco Paulo


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);
like image 24
Naveed S Avatar answered Oct 28 '22 06:10

Naveed S