Java ';凌乱';字符串到int的转换

Java ';凌乱';字符串到int的转换,java,string,types,integer,Java,String,Types,Integer,在我的代码中,我需要将一个字符串转换为一个整数——该字符串来自元数据的提取,然后将元数据与数字数组及其相应的类型进行比较。不幸的是,字符串不仅仅包含数字,它还包含一些空格和括号,这意味着通常的: 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) i

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

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(例如)是我想要/需要的唯一部分,从“凌乱”字符串中获取此数字的最简单方法是什么?谢谢

您可以使用以下功能:

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

您可以使用以下选项:

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

正则表达式:
\\d+
。。或者简单地说:
genre.replaceAll([^0-9],”)正则表达式:
\\d+
。。或者简单地说:
genre.replaceAll([^0-9],”)
您不需要
trim()
,因为空格也将被替换。请注意,如果有两个数字,这将连接它们,这可能不是您想要的。@marounnaroun是的,您是对的。Dan,我想我们可以考虑很多情况,但我的回答是基于这个问题中的输入。你不需要
trim()
,因为空格也会被替换。请注意,如果有两个数字,这将连接它们,这可能不是你想要的。@maroun maroun是的,你是对的。丹,我想我们可以考虑很多案例,但我的回答是基于这个问题的输入。