[英]How to obtain the info inside a String without length and indexOF. (JAVA)
I have an api which returns a String in the following format:我有一个 api,它返回以下格式的字符串:
ACTNEW_38_0001,ACTO_57999
I need to extract the numerical values (57999, or 38_0001) but:我需要提取数值(57999 或 38_0001)但是:
1: They can arrive in different order. 1:他们可以以不同的顺序到达。
2: It can arrive only one of them. 2:只能到其中一个。
3: It has to be lightweight. 3:它必须是轻量级的。
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. 1:我认为应该有更好的方法来实现这一点。
2: I haven´t tried yet the arrayUtils.indexOf
. 2:我还没有尝试过
arrayUtils.indexOf
。 If it doesn´t work I would have to do a contains, probably inside a for loop, but I think it´sa bad idea for something so simple.如果它不起作用,我将不得不做一个包含,可能在 for 循环内,但我认为对于如此简单的事情来说这是个坏主意。
Any help would be appreciated.任何帮助,将不胜感激。 Thanks
谢谢
You could use a regex find all approach on your CSV string:您可以在 CSV 字符串上使用正则表达式查找所有方法:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.