【问题标题】:Extracting integers from string of text in Java [duplicate]从Java中的文本字符串中提取整数[重复]
【发布时间】:2015-06-01 02:49:54
【问题描述】:

我有几行文字,例如:

"you current have 194764bleh notifications"
"you current have 32545444bleh notifications"
"you current have 8132bleh notifications"
"you current have 93bleh notifications"

从文本中获取整数的最佳方法是什么?

目前使用line.split 两次,一次用于“have”,一次用于“bleh”。
仅仅为了得到整数,这样做似乎效率很低。

有没有更好的方法来做到这一点?

【问题讨论】:

  • 这很好(恕我直言),按子字符串分割比使用正则表达式更快。
  • @alfasin 对于“更快”的一些无用定义。对于这个特定的临时任务,正则表达式更清晰、更易于维护。少数“浪费”的 CPU 周期无关紧要。不需要应用微基准。
  • 这里已经有解决方案了stackoverflow.com/questions/4030928/…
  • @user2864740 我想这取决于这个方法会被调用多少次。两个拆分与一个正则表达式对我来说似乎很公平(我不会因为在我维护的代码中找到其中任何一个而感到恼火)。如果这是 10 次拆分与一个正则表达式的权衡,我肯定会同意你的观点,但在这种情况下 - 我对两者都很好。

标签: java


【解决方案1】:

例如

String str = "you current have 194764bleh notifications";
str = str.replaceAll("\\D", ""); // Replace all non-digits

使用正则表达式删除所有非数字将是一种选择,
它也不会限制您使用 'have' 和 'bleh' 包装数字。

与使用 split 相比,不完全确定效率。

【讨论】:

  • 效率可能无关紧要(这会很快)。它确实改变了语义,因此它会接受"Hello 12 World 34",但需要注意的是——如果这些放松是可以的,那么我会使用类似的东西。
【解决方案2】:

您可以从上面的行中获取一个子字符串,然后将其转换为 int。

String strVal1 = line2.substring(17, line2.indexOf("bleh"));
int intVal1 = Integer.parseInt(strVal1);

我认为字符串格式是相同的。如果不是,您可以将开始索引更改为“有”的索引。

【讨论】:

    【解决方案3】:

    最近我喜欢使用正则表达式来提取我需要的字符串。所以我想使用如下方法:

    String a = "you current have 194764bleh notifications";
    
    Pattern numPattern = Pattern.compile("(\\d+)");
    Matcher theMather = numPattern.matcher(a);
    if(theMather.find())
    {
        System.out.println(theMather.group(1));
    }
    

    我已经测试了代码。希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2020-03-30
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      相关资源
      最近更新 更多