Sunday, 2 June 2019

Regular Expressions in Java



To check it is a valid mobile or not:
A mobile number is valid if the starting digit is either 7 or 8 or 9
and must also contain 10 digits

String st="7123456789"

if(st.matches("[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"))
        System.out.println("valid mobile");

(or)
if(st.matches("[7-9][0-9]{9}"))
        System.out.println("valid mobile");
(or)
if(st.matches("[789][0-9]{9}"))
        System.out.println("valid mobile");

if u want to allow 11 digit mobile number then first digit must be zero
if(st.matches("0? [7-9][0-9]{9}"))
        System.out.println("valid mobile");

0? means atmost one zero as first digit 
0 means compulsory one zero as first digit
0+ atleast one 0
0* means  0 may be there or may not be there and 0 can occur any number of times.

if u want to allow 10 or 11 or 12 digit mobile number then 
if(st.matches("(0|91)? [7-9][0-9]{9}"))
        System.out.println("valid mobile");

For email the regular expressions is
[a-z A-Z 0-9]@[a-z A-Z]. [a-z]{2-3}

=========
[^abc]  --means except abc

No comments:

Post a Comment