Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Java字符串中提取数字_Java_Regex - Fatal编程技术网

从Java字符串中提取数字

从Java字符串中提取数字,java,regex,Java,Regex,我有一个看起来像url的字符串。例如: .com/ - finds nothing .com - finds nothing /me - finds nothing /me/ - finds nothing /me/500/hello - finds nothing /me/12/test/550 - I need find 550 /test/1500 - I need find 1500 /test/1500/ - I need f

我有一个看起来像url的字符串。例如:

.com/ - finds nothing
.com - finds nothing
/me - finds nothing
/me/ - finds nothing
/me/500/hello - finds nothing
/me/12/test/550        - I need find 550
/test/1500             - I need find 1500
/test/1500/            - I need find 1500
我需要提取最后的数字,现在我这样做

int index = url.lastIndexOf('/');
String found = url.substring(index + 1, url.length());
if(Pattern.matches("\\d+", found)) {
 // If found digits at the end doSometihng
}
但是我不喜欢这个解决方案,如果我在最后加了斜杠,它就不起作用了。
捕捉最后一个数字的好方法是什么

我相信以下代码可以满足您的需要:

public Integer findLastInteger(String url) {
  Scanner scanner = new Scanner(url);
  Integer out = null;
  while(scanner.hasNextInt())
    out = scanner.nextInt();
  return out;
}

此代码返回最后一个整数(如果有),如果没有,则返回
null

如果后面没有任何其他数字,则该数字是最后一个。在正则表达式中:

public static void findLastNumber() {
  String str = "/me/12/test/550/";
  Pattern p = Pattern.compile("(\\d+)(?!.*\\d)");
  Matcher m = p.matcher(str);
  if (m.find()) {
    System.out.println("Found : " + m.group());
  }
}
您可以测试这个正则表达式

输出为:

/test/250/1900
1500
/
您将需要抓取组(2)。

试试这个正则表达式

.*\/(\d+)\/?
第一个捕获组是您的号码


此解决方案还将查找大小写
/me/500/hello-->500
。在这种情况下,我不需要查找它。如果数字始终位于字符串的末尾,则不需要进行前瞻。
.*\/(\d+)\/?