简体   繁体   中英

Regex to match a String with asterisk

I'm coding in Java and I want to split my string. I want to split it at.

/* sort */

Yes I plan to split a .java file that I have read as a string so I need it to include "/* sort */". I'm creating a code that sorts Arrays that are predefined in java class file.

Exactly that and do another split at

}

and then I wanted help how to go about splitting up the array since I'll be left with

an example would be this

final static String[] ANIMALS = new String[] /* sort */ { "eland", "antelope", "hippopotamus"};

My goal would be to sort that Array inside a .java file and replace it. This is my current code

    private void editFile() throws IOException {
    //Loads the whole Text or java file into a String
    try (BufferedReader br = new BufferedReader(new FileReader(fileChoice()))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        everything = sb.toString();
    }
    arrayCutOff = everything.split("////* sort *////");
    for(int i = 0; i < arrayCutOff.length; i++){
        System.out.println(arrayCutOff[i]);
    }
}

This basically reads the whole .txt or .java file completely with the exact same formatting into one string. I planned to split it at /* sort */ and sort the array inside but I realized if I did that I probably can't replace it.

Considered your're using java 8 you might go this direction:

private void editFile() throws IOException {
  List<String> lines = Files.readAllLines(Paths.get(fileChoice()));
  String content = lines.stream().collect(Collectors.joining(System.lineSeparator()));
  Stream.of(content.split(Pattern.quote("/* sort */"))).forEach(System.out::println);
}

However, the trick you're asking for is Pattern.quote , which dates back Java 5. It'll qoute a literal so it can be used as a literal in regExs and is a bit more convenient (and reliable I think) than wrestling around with backslashes...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM