如何在没有长度和索引的字符串内获取信息。 (Java)

发布于 2025-01-25 21:14:28 字数 871 浏览 1 评论 0原文

我有一个API,该API以以下格式返回字符串:

actNew_38_0001,acto_57999

我需要提取数值(57999,或38_0001),但:

1:1:它们可以以不同的顺序到达。

2:它只能到达其中一个。

3:必须轻量级。

我粗略地知道该怎么做。我的实际代码看起来或多或少像这样:

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 "";
    }

事实是:

1:我认为应该有更好的方法来实现这一目标。

2:我还没有尝试过arrayutils.indexof。如果它不起作用,我必须在一个循环中进行包含,但我认为这是如此简单的事情是坏主意。

任何帮助将不胜感激。谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里梦着梦中梦 2025-02-01 21:14:28

您可以使用正则判处查找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]

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]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文