java - 获取字符串中的特定数字

标签 java parsing

我正在尝试解析文本并从文本中获取值,例如:

Page 1 of 6

我正在考虑使用 java 提取结束号码。 所以在这种情况下我的输出应该是 6。

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

最佳答案

您可以为此使用正则表达式(它比使用例如 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);
    }
}

输出:

parsed page = 1 and pages = 6.

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

相关文章:

java - 如何映射 Map<String,Double>

python - 在 Python (Django) 中解析文本

php - XML 使 PHP 出现意外的字符串错误

android - JSON 解析帮助

ios - Swift 4 从JSON中获取相关数据

java - java 升级到 1.8 时解压文件时出现问题

java - Spring 模型属性在请求中获取 null

java - 将 Android Studio 项目迁移到桌面应用程序

java - 向 JChart2D 的 ChartPanel 添加弹出菜单项

java - 为什么我在解析 JSON 时得到 NULL 值