ADS

2 Ways To Match A Number In Regex

Java regex logo image created using Inkscape 2 Ways to match a number in Regex
Here are 2 simple ways, how you can match any number or a number with given no.of digits in Java using the regular expression. This is dead simple. The jadwal below comes with helpful commentaries that will give you the best understanding on how to do it.



 import java.util.*;
import java.util.regex.*;
class NumRegex
{
    public static void main(String args[])
    {
        // Create a regular expression that matches
        // any number
       
        // You know all this! This is why you came here ;)
        // What matches and what doesn't?
        // 1 matches
        // 24133242 matches
        // 2342332d doesn't match (it contains d at last!)
        // 23432 233 doesn't match (it contains a space)
        // asdfsafd doesn't match (it is not a number)
       
        // What's the +?
        // More 1 or more than 1 digit
        // \\d is for a signle digit
        String numRegex="^[\\d]+$";
       
        // This is another way, isn't it lengthy?
        // Yet, remember it!
        // String numRegex="^[0-9]+$";
       
        // Hmm, one more. What if i want only a 2 digit number
        // Replace 2 with whatever you no.of digits you want in
        // the number.
        // String numRegex="^[\\d]{2}$";
       
        // Create a Scanner object
        Scanner s=new Scanner(System.in);
       
        // Give the regex for compilation.
        // Don't worry, it gives a Pattern object in return! ;)
        Pattern p=Pattern.compile(numRegex);
       
        // Ask the user to enter a number, else he
        // scratches his head of what to do!
        System.out.println("Enter the number");
       
        // Read a line, use nextLine(). If you forgot
        // Line and simply use next(), you don't get spaces!
        String st=s.nextLine();
       
        // Create a Matcher, not a match box! ;)
        // See if what user has given is a number!
        Matcher m=p.matcher(st);
   
       
        // Now, print whether the user understood what we said!
        System.out.println(m.matches()?"You entered a number! Great! you understood the question :)":"I asked for number!!!!");
    }
}

Here is another one, to match a number that has between i to n digits, say for example, 1 to 4 digits, then you would simply write "^[\\d]{1,4}$";
If you love the post, the only way to show it is sharing, that is what you can give to me, do it only if you find this helpful. Don't otherwise.

Subscribe to receive free email updates:

ADS