-2

I want to check if my number matches a regex pattern.

What I want to achieve is to make a check if a number matches the pattern and than execxuting code.

My if statement is the following:

public String refactorNumber(String input){
    if(input.matches("#,##0.##")) {
       //execute code
    }
}

But it never matches, my input numbers are:

 - 0
 - 100
 - 1,100.01

What am I doing wrong?

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
Jonas
  • 769
  • 1
  • 8
  • 37

3 Answers3

0

It looks like you haven't understood the regular expression syntax properly I'm afraid.

From your sample code, it looks like you are trying to match a digit, followed by a comma, followed by two digits, followed by a zero, followed by a decimal point, followed by two digits.

To do that, your regular expression pattern would need to be:

\d,\d{2}0\.\d{2}

A great resource for figuring out patterns is this regex cheat sheet:

https://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

Unfortunately that site is having problems right now, so you can use this google search to find it:

https://www.google.co.uk/search?q=regex+cheat+sheet&tbm=isch

kabadisha
  • 670
  • 4
  • 15
0

You could do it this way (correct me if I am doing it wrong):

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public static void main(String[] args) {

    String input =" - 0\n"+
      " - 100\n"+
      " - 1,100.01\n"+
      " - 100,100,3\n"+
      " - 100,100,3.15\n"+
      "";  
    refactorNumber(input);  
}

public static void refactorNumber(String input){
    Matcher m = Pattern.compile("((?:\\d,)?\\d{0,2}0(?:\\.\\d{1,2})?)(?!\\d*,)").matcher(input);
    while (m.find()) {
        //execute code
    }
Quinn
  • 4,394
  • 2
  • 21
  • 19
0

Here is a simple line of code I like to use to detect only numbers.

if (input.matches("[0-9]*") {
//code here
}
Eddy Zavala
  • 549
  • 1
  • 4
  • 12