Home > other >  Substring a string in JAVA
Substring a string in JAVA

Time:10-06

Is possible to substring this String = "D:/test/for test/change.txt:D:/test/for test/further.txt:D:/test/for test/yandex.txt" to:

D:/test/for test/change.txt

D:/test/for test/further.txt

D:/test/for test/yandex.txt

Because are two column, I can not split() use ":".

CodePudding user response:

A simple regular expression below splits on ":" that are followed by a "driveletter:"

String s = "D:/test/for test/change.txt:D:/test/for test/further.txt:D:/test/for test/yandex.txt";
s.split(":(?=\\w:)");
==> String[3] { "D:/test/for test/change.txt"
              , "D:/test/for test/further.txt"
              , "D:/test/for test/yandex.txt" }

Note that this won't help if additional paths don't begin with driveletter:

CodePudding user response:

It looks to me like you want to split on a colon whenever it's not followed by a slash. For that, the regular expression you need is a "negative lookahead", which means "not followed by". So you should write myString.split(":(?!/)") - the (?! ) is how to write the negative lookahead.

CodePudding user response:

You can simply split it on :(?=[A-Za-z]:\/) which can be explained as

  • : : The character :
  • (?= : Start of lookahead
    • [A-Za-z] : An alphabet
    • :\\/ : The character : followed by /
  • ) : End of lookahead

Demo:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "D:/test/for test/change.txt:D:/test/for test/further.txt:D:/test/for test/yandex.txt";
        String[] paths = str.split(":(?=[A-Za-z]:\\/)");
        Arrays.stream(paths).forEach(System.out::println);
    }
}

Output:

D:/test/for test/change.txt
D:/test/for test/further.txt
D:/test/for test/yandex.txt

ONLINE DEMO

  • Related