简体   繁体   中英

Java regex match number pattern

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?

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

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
    }

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

if (input.matches("[0-9]*") {
//code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM