gpt4 book ai didi

java - Java从字符串中提取数字

转载 作者:行者123 更新时间:2023-11-30 08:56:27 24 4
gpt4 key购买 nike

我有一个看起来像 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 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());
}
}

你可以测试这个正则表达式here .

关于java - Java从字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28596282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com