正则表达式从单个组中的java中的字符串中查找整数或小数? [英] Regex to find integer or decimal from a string in java in a single group?

查看:708
本文介绍了正则表达式从单个组中的java中的字符串中查找整数或小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个示例字符串上尝试(\d + | \d + \.\d +)

I am trying (\d+|\d+\.\d+) on this sample string:

Oats     124   0.99        V    1.65

但它是当我在Java中使用模式匹配器类时,在不同的组中给出十进制数。

but it is giving me decimal number in different groups when I am using pattern matcher classes in Java.

我希望我的答案在一个组中。

I want my answers in a single group.

推荐答案

您不需要为整数和浮点数设置单独的模式。只需将小数部分设为可选,您就可以从一个组中获得两种类型的数字。

You don't need to have a separate patterns for integer and floating point numbers. Just make the decimal part as optional and you could get both type of numbers from a single group.

(\d+(?:\.\d+)?)

使用上述模式并从组索引中获取数字1。

Use the above pattern and get the numbers from group index 1.

DEMO

代码:

String s = "Oats     124   0.99        V    1.65";
Pattern regex = Pattern.compile("(\\d+(?:\\.\\d+)?)");
 Matcher matcher = regex.matcher(s);
 while(matcher.find()){
        System.out.println(matcher.group(1));
}

输出:

124
0.99
1.65

模式说明:


  • () 捕获群组。

  • \ + + 匹配一个或多个数字。

  • (?:) 非捕获组。

  • (?:\。\ d +)?匹配一个点和以下一个或多个数字。非捕获组使整个非捕获组成为可选项后,

  • () capturing group .
  • \d+ matches one or more digits.
  • (?:) Non-capturing group.
  • (?:\.\d+)? Matches a dot and the following one or more digits. ? after the non-capturing group makes the whole non-capturing group as optional.

只有更改模式的顺序时,正则表达式才有效。

Your regex will also work only if you change the order of the patterns.

(\d+\.\d+|\d+)

DEMO

这篇关于正则表达式从单个组中的java中的字符串中查找整数或小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆