java - Can't seem to split String by new line regex -


i have method, , not correctly add split string list.

public static list<string> formatconfigmessages(fileconfiguration config, string key, boolean colour, object... regex) {     list<string> messages = new arraylist<>();     if (config.islist(key)) {         config.getstringlist(key).foreach(message -> {             if (message.contains("\\n")) {                 collections.addall(messages, message.split("\\r\\n|\\n|\\r"));             } else {                 messages.add(message);             }         });     } else {         string message = config.getstring(key);         if (message.contains("\\n")) {             collections.addall(messages, message.split("\\r\\n|\\n|\\r"));         } else {             messages.add(message);         }     }     return messages.stream().map(message -> formatmessage(message, colour, regex)).collect(collectors.tolist()); } 

for bit of context, method used format configurable messages spigotmc plugin. method takes 4 parameters:

  1. fileconfiguration - class made simplify use of yaml configuration files.
  2. string - key of message (can indexed '.', either side of '.' represents different level of yaml file).
  3. boolean - whether or not reserved characters in string should converted coloured characters (colours can seen client)
  4. object... - patterns, etc.) <name> replaced following value in array.

that chunk of code won't work. initially, attempted set regex \n, didn't return list. assumed because searching parsed new lines rather '\n' stream of characters. changed regex \n, still didn't work. search internet , found in this post should use regex \\r\\n \\n because \r used on windows systems. again did not work, , keep getting 1 string \n still inside.

here's why.

regex has own escape sequences, denoted \\ (the escape sequence \), since java reserves \.

for example, \\w denotes character in word.

to split "\n", you'll need \\\\n instead, because \\n in regex represents actual line break, \n represents 1 in java.

example:

system.out.println(arrays.tostring("hello\\nworld".split("\\\\n"))); system.out.println(arrays.tostring("hello world\nwith newline".split("\\n"))); system.out.println(arrays.tostring("hello world\nwith newline".split("\n"))); system.out.println(arrays.tostring("i won't\\nsplit".split("\\n"))); 

prints:

[hello, world] [hello world, newline] [hello world, newline] <-- same effect above [i won't\nsplit] 

additionally, handle 3 line end types (though \r on own uncommon nowadays), use regex \\\\r?\\\\n|\\\\r instead.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -