Accept Only 0-9 Numbers RegEx Example


If you are trying to write a validation code that can accept only numbers between 0-9 digits, then you can make use of the below RegEx (Regular Expression)

Expression:
^[0-9]+$
Explanation:
  1. ^ : The caret or circumflex is used to assert the start of the string.
  2. [0-9] : To matches any digit between 0 and 9.
  3. + : matches the previous character (i.e. [0-9]) one or more times.
  4. $ : Dollar sign asserts the end of the string.

Example: Java

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

public class RegEx {

    public static void main(String[] args) {

        final String regex = "^[0-9]+$";
        final String str = "100\n"
	 + "abc";
        
        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(str);
        
        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }
    }
}


Example: Python

import re

# Define the regular expression
regex = r"^[0-9]+$"

# Test the regular expression on some sample strings
strings = ["123", "abc", "12a", "java", "a456", "12.34"]

for string in strings:
    if re.match(regex, string):
        print(f"{string} matches the regex")
    else:
        print(f"{string} does not match the regex")

Example: GoLang

package main

import (
    "fmt"
    "regexp"
)

func main() {

    regex := regexp.MustCompile("^[0-9]+$")


    strings := []string{"123", "anc", "8910", "123a", "a456", "12.34"}
    for _, str := range strings {
        if regex.MatchString(str) {
            fmt.Printf("%s matches the regex\n", str)
        } else {
            fmt.Printf("%s does not match the regex\n", str)
        }
    }
}

Example: PHP

<?php

$regex = "/^[0-9]+$/";

$strings = array("123", "abc", "1a", "123a", "a456", "12.34");

foreach ($strings as $string) {
    if (preg_match($regex, $string)) {
        echo "$string matches the regex\n";
    } else {
        echo "$string does not match the regex\n";
    }
}
?>

Example: JavaScript

let regex = /^[0-9]+$/;


let strings = ["123", "abc", "122x", "123a", "a456", "12.34"];

for (let string of strings) {
    if (regex.test(string)) {
        console.log(`${string} matches the regex`);
    } else {
        console.log(`${string} does not match the regex`);
    }
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap