Siro Duschletta
Siro Duschletta

Reputation: 303

How can I split by the last point of a String?

I know I can split strings like this

String myString = "foo.bar";    
List<String> strings = Arrays.asList(myString.split("."));

But my String looks like 20151221.1051.Test.01.properties, it can have any number of dots, and I want to remove the .properties at the end (only by the last dot).

Upvotes: 8

Views: 13450

Answers (6)

Kiran K
Kiran K

Reputation: 768

It looks like your question is more about getting the File Name minus extension. There are enough open source libraries out there that can help you get this done. For example: Apache Commons IO: https://commons.apache.org/proper/commons-io/apidocs/index.html?org/apache/commons/io/FileUtils.html

There is a method called getBaseName() that helps you get the name of the file minus full path and minus the extension. Another method called getExtension() will only get you the extension of the file. Slice and dice all you want!

Upvotes: 0

Abdelhak
Abdelhak

Reputation: 8387

Try to use this:

 String myString = "20151221.1051.Test.01.properties";    
    List<String> strings = Arrays.asList(myString.substring(0,myString.lastIndexOf(".")).split("\\.(?=[^\\.])"));
    for (String string : strings) {
        System.out.println(string);

    }

With myString.substring(0,myString.lastIndexOf(".")) the file extension and with split split("\\.(?=[^\\.])") you have output:

  20151221
  1051
  Test
  01

Upvotes: 0

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

You are almost there with your code :) a small change would fetch you what you need :)

Here's what you can do:

String myString = "201512211051.Test.01.properties";    
List<String> strings = Arrays.asList(myString.split("."));
strings.set(strings.size() - 1,"");

now you have replaced the last part of split array :) join the list to create string. Use whichever way pleases you :) either loop through elements or use String.join provided in ios 8 :)

Upvotes: 0

El maik
El maik

Reputation: 59

You could solve that using substring method like this:

string test = "20151221.1051.Test.01.properties"
test = test.Substring(0, test.LastIndexOf('.'))

Hope that helps!

Upvotes: 0

assylias
assylias

Reputation: 328737

If you want to use split, you need to escape the dot (split expects a regular expression).

List<String> strings = Arrays.asList(myString.split("\\."));

If you only need to remove the last part, you can use replaceAll and a regex:

myString = myString.replaceAll("\\.[^.]*$", "");

Explanation:

  • \\. looks for a dot
  • [^.]* looks for 0 or more non dot characters
  • $ is the end of the string

Upvotes: 2

Eran
Eran

Reputation: 393936

Use myString.lastIndexOf(".") to get the index of the last dot.

For example, if you are sure that your input String contains at least one dot :

String name = myString.substring(0,myString.lastIndexOf("."));

Upvotes: 12

Related Questions