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`);
}
}
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
More Posts related to HowTos,
- [Fix] Error 1020 Cloudflare: Access was denied
- What is an Authorization Code Grant? OAuth 2.0
- Fix: psql: error: connection to server at localhost (::1) port 5432 failed: FATAL: database does not exist
- 100+ SEO Tips to improve your website search ranking
- How to submit website to dmoz directory
- How to check the version of NodeJS installed
- How to enter Rockstar Activation Code?
- Background task activation is spurious error - Windows 10, Office 2016, Office 365
- Angular CLI ng Error: You need to specify a command before moving on. Use --help to view the available commands
- cURL HTTP GET request command examples
- Fix - JioCinema Something Went Wrong Please Try Again Error 8001 while streaming IPL Cricket Live
- How to remove password from pdf file
- How to identify the version of IntelliJ
- Command: How to scp a file to remote server location?
- How to add Widgets to MacBook Desktop
- Setting up RSS feeds notifications within Outlook
- Fix - Website Connection timed out Error Code 522 (Cloudflare)
- How to fix: Please check your network connection (Retry)
- Fix: Could not connect to Redis at 127.0.0.1:6379: Connection refused
- Accept Only 0-9 Numbers RegEx Example
- How to create a New Project in Visual Studio Code (VS Code)
- Top 10 emerging breakthrough trending technologies
- Free Unlimited Calls from MTNL & BSNL Landlines from 1st May 2015
- [Error] zsh: command not found: mvn
- How to Scan iPhone for Virus? Is Antivirus it really required?
More Posts:
- Android Development - How to switch between two Activities - Android
- Create simple struts2 project using maven commands - Java
- Increase or Decrease macOS Sonoma Sidebar Icon and Text Size - MacOS
- How to Measure Execution Time in Jupyter Notebook Cell - Python
- Python: Convert Minutes to Hours - Python
- Where are Plugins Installed in Notepad++ - NotepadPlusPlus
- [Android Studio] Error: Missing system image on device - Android-Studio
- How to hide toolbar on Notepad++ - NotepadPlusPlus