I have an api which returns a String in the following format:
ACTNEW_38_0001,ACTO_57999
I need to extract the numerical values (57999, or 38_0001) but:
1: They can arrive in different order.
2: It can arrive only one of them.
3: It has to be lightweight.
I roughly know how to do it. My actual code looks more or less like this:
private final String tipoActivity = "ACTO_"; private String obtenerSplitOldElem(String toSplit) { if(toSplit.contains(",")) { String[] split = toSplit.split(","); int element = ArrayUtils.indexOf(toSplit, "ACTO_"); String split2[] = split[element-1]; return split2[1]; } else { String[] split = split.split("ACTO_"); return split[1]; } return ""; }
The thing is that:
1: I think there should be a better way to achieve this.
2: I haven´t tried yet the arrayUtils.indexOf
. If it doesn´t work I would have to do a contains, probably inside a for loop, but I think it´s a bad idea for something so simple.
Any help would be appreciated. Thanks
Advertisement
Answer
You could use a regex find all approach on your CSV string:
String input = "ACTNEW_38_0001,ACTO_57999"; List<String> nums = Pattern.compile("\d+(?:_\d+)*") .matcher(input) .results() .map(MatchResult::group) .collect(Collectors.toList()); System.out.println(nums); // [38_0001, 57999]