获取字符串中的特定数字

The*_*ner 0 java parsing

我试图解析文本并从文本中获取值,如:

Page 1 of 6
Run Code Online (Sandbox Code Playgroud)

我正在寻找使用java提取结束号码.所以我在这种情况下的表现应该是6.

我可以使用任何java字符串函数吗?(或)任何其他方式?

dac*_*cwe 15

你可以使用正则表达式(比例如使用它更安全String.split):

public static void main(String[] args) {

    String text = "Page 1 of 6";

    Matcher m = Pattern.compile("Page (\\d+) of (\\d+)").matcher(text);

    if (m.matches()) {
        int page  = Integer.parseInt(m.group(1));
        int pages = Integer.parseInt(m.group(2));

        System.out.printf("parsed page = %d and pages = %d.", page, pages);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

parsed page = 1 and pages = 6.
Run Code Online (Sandbox Code Playgroud)


Dan*_* D. 8

像这样的东西:

String s = "Page 1 of 6";
String[] values = s.split(" ");
System.out.println(Integer.parseInt(values[values.length - 1]));
Run Code Online (Sandbox Code Playgroud)