Java 整数或双精度的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18415065/
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-08-12 01:25:01  来源:igfitidea点击:

regex for integer or double

javaregex

提问by

There is a string "12.2A12W99.0Z0.123Q9" I need to find 3 groups: (double or int)(nondigit)(double or int) So in the case of the sample, I would want this to happen:
matcher.group (1) = "12.2"
matcher.group (2) = "A"
matcher.group (3) = "12"

有一个字符串 "12.2A12W99.0Z0.123Q9" 我需要找到 3 个组:(double or int)(nondigit)(double or int) 所以在示例的情况下,我希望这种情况发生:
matcher.group (1) = "12.2"
matcher.group (2) = "A"
matcher.group (3) = "12"

My current regex only matches against integers: "^(\d+)(\D)(\d+)" So I am looking to change the group (\d+) to something that will match against integers OR doubles.

我当前的正则表达式只与整数匹配:“^(\d+)(\D)(\d+)”所以我希望将组 (\d+) 更改为与整数匹配或加倍的内容。

I dont understand regex at all, so explaining like I'm 5 would be cool.

我根本不懂正则表达式,所以像我 5 岁那样解释会很酷。

回答by Yogesh Tatwal

try below code :- Your regular expression is only matching numeric characters. To also match the decimal point too you will need:

尝试以下代码:-您的正则表达式仅匹配数字字符。要也匹配小数点,您将需要:

Pattern.compile("\d+\.\d+")

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

The . is escaped because this would match any character when unescaped.

这 。被转义,因为这在未转义时将匹配任何字符。

Note: this will then only match numbers with a decimal point which is what you have in your example.

注意:这将只匹配带有小数点的数字,这就是您在示例中所拥有的。

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

public void testInteger() {
    Matcher m =p.matcher("10");

    assertTrue(m.find());
    assertEquals("10", m.group());
}

public void testDecimal() {
    Matcher m =p.matcher("10.99");

    assertTrue(m.find());
    assertEquals("10.99", m.group());
}