blue-sky
blue-sky

Reputation: 53896

Regular expression to truncate a String

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

Answers (7)

Reimeus
Reimeus

Reputation: 159844

You could simply use

test1.substring(0, 10) + "..." + test1.substring(test1.lastIndexOf('.'))

Upvotes: 3

Subhrajyoti Majumder
Subhrajyoti Majumder

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

Prateek
Prateek

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

Francisco Paulo
Francisco Paulo

Reputation: 6322

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

test1.replaceAll("(.{0,10}).*(\\..+)","$1...$2")

Upvotes: 8

Naveed S
Naveed S

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

Lincoded
Lincoded

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

gefei
gefei

Reputation: 19856

For this simple task you don't need Regex

String p1 = test1.substring(0, 10) + "..." + test1.substring(test1.lastIndexof('.'));

Upvotes: 0

Related Questions