1

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"

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.

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

  • 3
    the first entry when searching the web returns: [Matching Floating Point Numbers with a Regular Expression](http://www.regular-expressions.info/floatingpoint.html) and it answers your question – Op De Cirkel Aug 24 '13 at 05:00

1 Answers1

1

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());
}
Yogesh Tatwal
  • 2,722
  • 20
  • 43
  • 2
    What's a `:-`? I can't rotate my mouth like that. – Cole Tobin Aug 24 '13 at 05:22
  • Thank you very much for this, but I want it to amtch against both integers and doubles, not just doubles. Is there a way to write a regex to do that? –  Aug 24 '13 at 05:30
  • Just now my edited answer and let me know your feedback – Yogesh Tatwal Aug 24 '13 at 05:38
  • @YogeshTatwal But now I think the groups are messed up because of the extra brackets, I need matcher.group(1) to return the first number, matcher.group(2) to return the non-digit, etc. The extra brackets mess up the grouping. –  Aug 24 '13 at 05:52
  • As par your requirement i have edited it again – Yogesh Tatwal Aug 24 '13 at 05:56