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:
- ^ : The caret or circumflex is used to assert the start of the string.
- [0-9] : To matches any digit between 0 and 9.
- + : matches the previous character (i.e. [0-9]) one or more times.
- $ : 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`);
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!