I have a problem. For my code I have a config file with the following content:
updateOnInsert=true removeLast=false names=Joey Greek, Lisa Blessing, Arnold Verdict
To read this config file, I have the following code:
ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream is = classloader.getResourceAsStream("configs/main.config"); // Read all properties from agent strategy file Properties properties = new Properties(); properties.load(is); // Assign all properties to variables boolean updateOnInsert = Boolean.parseBoolean(properties.getProperty("updateOnInsert")); boolean removeLast = Boolean.parseBoolean(properties.getProperty("removeLast")); List<String> names = Arrays.asList(properties.getProperty("names").split(", ", -1));
But now I need to change the format of the names to:
names=[[Joey, Greek], [Lisa, Blessing], [Arnold, Verdict]]
The output varialbe has to be of the type: String[][]
with as result:
[0] => [Joey, Greek] [1] => [Lisa, Blessing] [2] => [Arnold, Verdict]
What is the best way to achieve this?
Advertisement
Answer
Depends on what the input could look like. The safest way would probably be to use a proper parser (and maybe a different file format).
If the list is always in the form [[Name], [Name]]
and Name
never contains brackets, a simple way could be to use a more specialized regex, e.g. (?<=]),s*(?=[)
.
Rundown on the regex:
(?<=])
: a positive look-behind, i.e. any match must follow a]
.,s*
: the actual match to split at (and remove), i.e. a comma followed by any whitespace(?=[)")
: a positive look-ahead, i.e. any match must be followed by a[
.
Finally, split each of the names by ,
to get the 2D array:
//results in Strings like "[Joey, Greek]", "[Lisa, Blessing]", and "[Arnold, Verdict]" String[] completeNames = properties.getProperty("names").split("(?<=\]),\s*(?=\[)"); //We're using a stream here but you could as well use traditional loops String[][] namesInParts = Arrays.stream(completeNames) //map the name by removing the brackets and splitting at the comma (followed by any whitespace) .map(name -> name.replaceAll("[\]\[]", "").split(",\s*")) //collect everything into a new array .toArray(String[][]::new);