Java 使用正则表达式从字符串中提取数字

Java 使用正则表达式从字符串中提取数字,java,regex,Java,Regex,我有一个字符串,如下所示: String str="tile tile-2 tile-position-1-4" 我希望接收数组中的数字,例如[2,1,4] 我自己的解决方案是使用split中断字符串,但我想知道是否有使用Regx的快捷方式 感谢@nitzien with Regx,它尝试了: String pattern= "^tile tile-(\\d*) tile-position-(\\d*)-(\\d*)$"; Pattern r = Pattern.compile(pattern

我有一个字符串,如下所示:

String str="tile tile-2 tile-position-1-4"
我希望接收数组中的数字,例如
[2,1,4]

我自己的解决方案是使用
split
中断字符串,但我想知道是否有使用
Regx
的快捷方式

感谢@nitzien with Regx,它尝试了:

String pattern= "^tile tile-(\\d*) tile-position-(\\d*)-(\\d*)$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println(m.group(2));
但是,它抱怨:

java.lang.IllegalStateException: No match found
替换是字符串,您需要根据所使用的语言将其转换为数组

编辑问题后更新答案

String str="tile tile-2 tile-position-1-4";
String pattern= "^tile tile-(\\d*) tile-position-(\\d*)-(\\d*)$";
System.out.println(str.replaceAll(pattern, "$1,$2,$3"));
这将给

2,1,4

整个字符串中是否始终有三个数字?是的,这是一种模式。请尝试以下操作:
string[]result=Arrays.stream(str.split(“\\D”)).filter(s->!s.isEmpty()).toArray(string[]::new)我已经更新了我的问题,你知道吗?Matcher m=r.Matcher(classname);?这是
str
sorry请检查更新的答案
2,1,4