【问题标题】:'messy' string to int conversion java'混乱'字符串到int转换java
【发布时间】:2014-10-03 09:07:59
【问题描述】:

在我的代码中,我需要将字符串转换为整数 - 字符串来自元数据的提取,然后将其与数字数组及其对应的类型进行比较。不幸的是,字符串不只是包含数字,它包含一些空格和括号,这意味着通常:

String genre = mf.genre(byteArr);
 // this gets the metadata from the byte array (It's of no consequence to this but it makes it easier to understand)
int genreInt = Integer.parseInt(genre);
System.out.println(genreInt);

无效,返回

Exception in thread "main" java.lang.NumberFormatException: For input string: "    (13)"

由于 13(例如)是我想要/需要的唯一部分,从“混乱”字符串中获取这个数字的最简单方法是什么?谢谢

【问题讨论】:

  • 正则表达式:\\d+.. 或者简单地说:genre.replaceAll("[^0-9]", "");

标签: java string types integer


【解决方案1】:

您可以使用以下内容:

System.out.println(genre.replaceAll("[^0-9]",  ""));

【讨论】:

  • 你不需要trim(),因为空格也会被替换。
  • 请注意,如果有 2 个数字,这会将它们连接起来,这可能不是您想要的。
  • @MarounMaroun 是的,你是对的。丹,我认为我们可以考虑很多案例,但我根据这个问题的输入来回答。
猜你喜欢
  • 2014-01-25
  • 2013-11-03
  • 1970-01-01
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2016-07-07
相关资源
最近更新 更多