gpt4 book ai didi

java - 如何解析字符串并获取特定值

转载 作者:行者123 更新时间:2023-11-29 05:14:40 26 4
gpt4 key购买 nike

我应该像这样解析一个字符串:

casale-monferrato/incomincia-oggi-roma-l-ultimo-atto-processo-eternit-davanti-corte-cassazione-74506.html

我要保存的是字符串末尾的数字,"-"和 ".html" 之间的数字(在本例中为 74506)。

解析必须使用被认为是最后一个数字的唯一条件,不应考虑其他数字。

我如何在 java 中执行此操作?我必须使用的正确 regexp 是什么?

最佳答案

使用下面的正则表达式只匹配最后一个数字。

"(?<!\\d)\\d+(?=\\D*$)"

DEMO

String s = "casale-monferrato/incomincia-oggi-roma-l-ultimo-atto-processo-eternit-davanti-corte-cassazione-74506.html";
Pattern regex = Pattern.compile("(?<!\\d)\\d+(?=\\D*$)");
Matcher matcher = regex.matcher(s);
while(matcher.find()){
System.out.println(matcher.group(0));
}

输出:

74506

正则表达式:

(?<!                     look behind to see if there is not:
\d digits (0-9)
) end of look-behind
\d+ digits (0-9) (1 or more times)
(?= look ahead to see if there is:
\D* non-digits (all but 0-9) (0 or more
times)
$ before an optional \n, and the end of
the string
) end of look-ahead

关于java - 如何解析字符串并获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27014431/

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