Matching decimals in strings using matcher()

后端 未结 2 382
一个人的身影
一个人的身影 2021-01-24 22:17

I have a question regarding the matcher. Currently I am trying to read a string and store all the digits into an array. My question is, how do you try to match both integers and

2条回答
  •  逝去的感伤
    2021-01-24 22:37

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

提交回复
热议问题