Matching decimals in strings using matcher()

◇◆丶佛笑我妖孽 提交于 2020-01-11 11:51:29

问题


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 decimals?

I have an array of doubles called:

double[] thisArray = new double[20];

Into this array, i am trying to store all the numbers I extract from the string.

Matcher temp = Pattern.compile("(\d+)").matcher(x);

That is my function for the matcher. But this only matches integers. I want to match both integers and decimals like (5.2). But how do I do this? I want to be able to enter in both integers and decimals into my string.

Any help would be appreciated. Thanks!


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/5011855/matching-decimals-in-strings-using-matcher

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