vendredi 26 février 2021

Why isn't "\\" working as a delimiter pattern [duplicate]

I want to break down all the parents of a directory by using a simple Scanner and using "\\" as the delimiter.

import java.util.Scanner;

public class TestScanner {
    public static void main (String [] args) {
        String directory = "C:\\Users\\MyName\\New File";
        Scanner scanner = new Scanner(directory);
        scanner.useDelimiter("\\");
        while (scanner.hasNext()) {
            System.out.println(scanner.next());
        }
        scanner.close();
    }
}

However, I get an exception saying

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \
       at java.util.regex.Pattern.error(Pattern.java:1969)
       at java.util.regex.Pattern.compile(Pattern.java:1708)
       at java.util.regex.Pattern.<init>(Pattern.java:1352)
       at java.util.regex.Pattern.compile(Pattern.java:1028)
       at java.util.Scanner$1.create(Scanner.java:367)
       at java.util.Scanner$1.create(Scanner.java:365)
       at sun.misc.LRUCache.forName(LRUCache.java:72)
       at java.util.Scanner.useDelimiter(Scanner.java:1150)
       at TestScanner.main(TestScanner.java:7)

I've tried things like "[\\]+" and Pattern.compile("\\") but neither seem to work! Please help me out, and thanks in advance :)

Aucun commentaire:

Enregistrer un commentaire