Splitting a Regular
Expression
import java.util.regex.Pattern;
public class PatternSplitExample
{
public static void main(String args[])
{
Pattern p = Pattern.compile(" ");
String tmp = "this is the Java example";
String[] tokens = p.split(tmp);
for (int i = 0; i < tokens.length; i++)
{
System.out.println(tokens[i]);
}
}
}
Replace first occurrence of a
String
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
{
public static void main(String args[])
{
Pattern p = Pattern.compile("hello");
String instring = "hello hello hello.";
System.out.println("initial String: "+ instring);
Matcher m = p.matcher(instring);
String tmp = m.replaceFirst("Java");
System.out.println("String after replacing 1st Match: "+tmp);
}
}
Check Date Format
public class Main
{
public static void main(String[] argv)
{
boolean isDate = false;
String date1 = "8-05-1988";
String date2 = "08/04/1987" ;
String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}";
isDate = date1.matches(datePattern);
System.out.println("Date :"+ date1+": matches with
the this date Pattern:"+datePattern+"Ans:"+isDate);
isDate = date2.matches(datePattern);
System.out.println("Date :"+ date2+": matches with
the this date Pattern:"+datePattern+"Ans:"+isDate);
}
}
No comments:
Post a Comment