-1

I want to try a regex to match my string of this kind like

if (cadena.matches("[0-9],[0-9]")){

    Do something} //this being like if the string has numbers before and after the comma

Which way can I put this condition? An input example for the match could be cadena = "2,2345"

I have tried ".\d+,\d+." and ".[0-9],[0-9]." I have tried using my last try with "[0-9]+,[0-9]+" this says any more numbers and seems to work

Using the last one solved my question sorry for the effort.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • Check this out [Regular expression for floating point numbers](https://stackoverflow.com/questions/12643009/regular-expression-for-floating-point-numbers) And [Regular expression to match numbers with or without commas and decimals in text](https://stackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text) – H.Tibat Jun 24 '18 at 03:02
  • What have you already tried? Where did it go wrong? Because .... `\d+,\d+` sort of comes to mind – Tibrogargan Jun 24 '18 at 03:06

1 Answers1

0

the method matches(regex) matches the entire string.

You can change your pattern to match the entire string.

 if (cadena.matches(".*[0-9],[0-9].*")){
      // Do Something
 }

Or you could use find, to find a number comma number anywhere in the string:

 Pattern pattern = Pattern.compile("[0-9],[0-9]");
 if (pattern.matcher(cadena).find()){
      // Do Something
 }

If you wanted to actually use the numbers that matched both sides of the comma in your if block, you can use () to capture groups and refernce them with a Matcher.

    String cadena = "2,2345";
    Pattern pattern2 = Pattern.compile("([0-9]+),([0-9]+)");
    Matcher matcher = pattern2.matcher(cadena);
    if (matcher.find()){
        System.out.println("Found " + matcher.group(1) + " - " + matcher.group(2));
    }

    // Prints: Found 2 - 2345
D. May
  • 302
  • 1
  • 7