strings = Arrays.a...">

How can I split to the last point of a line?

I know I can break lines like this

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

But my line looks like it 20151221.1051.Test.01.properties, it can have any number of points, and I want to delete .propertiesat the end (only the last point).

+4
source share
6 answers

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

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

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

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 a replaceAllregular expression:

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

:

  • \\.
  • [^.]* 0
  • $ -
+2

, substring :

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

, !

0

:) , :)

:

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

:) . , : , String.join, ios 8:)

0

:

 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);

    }

myString.substring(0,myString.lastIndexOf(".")) split("\\.(?=[^\\.])") :

  20151221
  1051
  Test
  01
0

, . , . : Apache Commons IO: https://commons.apache.org/proper/commons-io/apidocs/index.html?org/apache/commons/io/FileUtils.html

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

0
source

Source: https://habr.com/ru/post/1621233/


All Articles