java 正则表达式从单个组中的java字符串中查找整数或小数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25707779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:30:56  来源:igfitidea点击:

Regex to find integer or decimal from a string in java in a single group?

javaregex

提问by Mimanshu

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

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

Oats     124   0.99        V    1.65

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

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

I want my answers in a single group.

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

回答by Avinash Raj

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+)?)

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

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

DEMO

演示

Code:

代码:

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));
}

Output:

输出:

124
0.99
1.65

Pattern explanation:

图案说明:

  • ()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.
  • ()捕获组。
  • \d+匹配一位或多位数字。
  • (?:)非捕获组。
  • (?:\.\d+)?匹配一个点和后面的一位或多位数字。?在非捕获组使整个非捕获组成为可选之后。

OR

或者

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

仅当您更改模式的顺序时,您的正则表达式也将起作用。

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

DEMO

演示

回答by walid toumi

Try this pattern:

试试这个模式:

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

Edit:
\d+ match 1 or more digit
(?: non capturing group (optional)
   \. '.' character
   \d+ 1 or more digit
)?  Close non capturing group 

回答by Adam

Question not entirely clear, but the first problem I see is . is a magic character in regex meaning any character. You need to escape it with as . There are lots of regex cheat sheets out there, for example JavaScript Regex Cheatsheet

问题不完全清楚,但我看到的第一个问题是 . 是正则表达式中的魔法字符,表示任何字符。你需要用 as 来逃避它。有很多正则表达式备忘单,例如JavaScript Regex Cheatsheet

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