CodesJava

Easy learning with example program codes

Java regex validate number


Regular expressions

Regular expressions represents a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. The abbreviation for regular expression is regex. In programming regular expressions are mainly used to define constraint on strings like password, email validation.

Regular expression to accept only digits

\d+$

This regular expression refers to a pattern which accepts only digits.

Example

package com.codesjava;
 
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexTest {
	private static final String PATTERN = "\d+$";
	public static void main(String args[]){ 
		List<String> values = new ArrayList<String>();	       
		values.add("Jai"); 
		values.add("12345345"); 
		values.add("1234567890");
 
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
		  System.out.println(matcher.matches());
		}
	}
}

Output

false
true
true
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki