Matching decimals in strings using matcher()

旧巷老猫 提交于 2019-12-02 03:59:54

This will handle both integer and decimals:-

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

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

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

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

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

The phrase \d+ will match a string of numbers. So what about adding a dot between two of them? (\d+)|(\d+|\.\d+)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!