Wednesday, 6 January 2016

How to check string contains numeric or alphabet in java string by using Regex(Regular Expression) ??

package org.cmania;

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

public class StringNumericRegex {

public static void main(String[] args)
{
   Pattern pat = Pattern.compile(".*\\d.*");   // for digit detection only

// Pattern pat = Pattern.compile("[a-zA-Z]+");  for alphabetic detection

// Pattern pat = Pattern.compile("[a-zA-Z ]*\\d+.*");  for digit detection

// org.apache.commons.lang.StringUtils.isAlpha(str); for alphabetic detection

String str = "java8";

/**
* Except for splitting a string, you need to create a Matcher object from the Pattern object.
* The Matcher will do the actual work. The adv of having two separate classes is that
* you can create many Matcher objects from a single Pattern object, and thus apply the
* regular expression to many subject strings simultaneously.
*/

Matcher match = pat.matcher(str);

if (match.matches())
{
     System.out.println("String contains numeric values");
}
else
{
                     System.out.println("String doesn't contain any numberic values");
}


}

}

No comments:

Post a Comment

JSP interview questions and answers

Q1. What is JSP and why do we need it? JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. J...