【问题标题】:How to filter/extract data from String? [duplicate]如何从字符串中过滤/提取数据? [复制]
【发布时间】:2016-06-18 00:41:28
【问题描述】:

如何在此处应用过滤器

 String x=Showing 138 of 138 String(s)

我只想得到138,结束值如何得到?

【问题讨论】:

标签: java


【解决方案1】:

你可以试试:

public static void main(String[] args) throws IOException {
    String x="Showing 158 of 138 String(s)";
    System.out.println(x.replaceAll(".*\\s(\\d+).*", "$1"));
}

O/P:138

【讨论】:

    【解决方案2】:

    我不会为此使用正则表达式,因为它不是灵活的解决方案。尝试解析字符串以获得有效值:

    String s =" String x=Showing 138 of 138 String(s)";
    String[] words = s.split(" ");
    BigDecimal value = null;
    for(String word : words) {
        try {
            value = BigDecimal.valueOf(word);
            } catch(NumberFormatException e) {}
        }
    System.out.println(value);
    

    【讨论】:

    • s.split(" "); ==> 你正在使用正则表达式:)
    • @TheLostMind 足够接近,但不是无法检测到双打;)
    • 好吧,OP 并没有说他想要小数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2021-03-06
    • 2019-10-15
    • 2019-04-24
    • 2019-12-18
    • 1970-01-01
    相关资源
    最近更新 更多