【问题标题】:Get number from the string (RegExp) [closed]从字符串中获取数字(RegExp)[关闭]
【发布时间】:2014-11-07 11:40:00
【问题描述】:

你能帮我写一个java正则表达式来从下一个字符串中获取数字吗:

  1. 动物 1 动物
  2. 1 只动物
  3. 动物 1

【问题讨论】:

  • 到目前为止你尝试过什么?
  • 匹配数字\\d+

标签: java regex


【解决方案1】:

stackoverflow 中有很多关于这个问题的答案。下次问之前先搜索一下!

这是一个简单的代码,可以满足您的需求:

String str= "animal 1 animal";

    Pattern p = Pattern.compile("-?\\d+");

    Matcher match = p.matcher(str);

    while (match.find()) {
        System.out.println(match.group());
    }

你的其他字符串也是一样的。只是改变“str”的值或创建另一个变量。

【讨论】:

    【解决方案2】:

    您可以使用PatternMatcher,如下所示:

    Matcher m = Pattern.compile("-?\\d+").matcher(myString);
    while (m.find()) {
        System.out.println(m.group()); // Use Integer.parseInt(m.group()); to get an int
    }
    

    【讨论】:

    • 这也能找到负数。
    • 5.45 也称为数字。
    • @AvinashRaj:OP 没有指定什么样的数字。如果您还想解析浮点数,那么您还需要考虑语言环境:在某些国家/地区,小数点分隔符不同,例如 5,45
    • >>OP没有指定什么样的数字。您可以在示例中找到整数。
    • @DarkDust op 也没有指定负数。
    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    相关资源
    最近更新 更多