Regular Expression in Java

Regular Expression in java are very important because when we are using strings then it conatins numbers,characters,special chracters etc. so by using this regular expression we can easily can extract the things from the string whatever we needed.

Ex:   String s =  "This is $100 Dollars % * ^";


  1.    To extract '$' from the string can be done using regular expressions.
  2.    To extract '100' from the String .
  3.    Only to get characters.
  4.    Excluding the spacing in the above string.



                     To extract '$' from the string can be done using regular expressions

         public class string_to_int
          {
public static void main(String[] args)
               {
         String s ="this is $100 Dollars % * ^ ";


String s2=s.replaceAll("\\w", "");
System.out.println(s2);

}

}

Output:

  $  %  *  ^
 
                   
                                       To extract '100' from the String 


public class string_to_int
{

public static void main(String[] args)
         {

String s ="this is $100 Dollars  % * ^ ";


int num=Integer.parseInt(s.replaceAll("\\D", ""));
System.out.println(num);


}

}

Output:

100




                Only to get characters From the String Excluding Integer and special characters



public class string_to_int 
{

public static void main(String[] args) 
             {
String s ="this is $100 Dollars % * ^ ";

String s2=s.replaceAll("\\W", ""); //To exclude special characters.
String s3=s2.replaceAll("\\d", ""); // To exclude numeric value.
System.out.println(s3);
}

}

Output:

thisisDollars




                               Excluding the spacing in the above string


public class string_to_int 
{
public static void main(String[] args) 
          {
String s ="this is $100 Dollars % * ^ ";
String s2=s.replaceAll("\\s", "");
System.out.println(s2);
}

}

Output:

thisis$100Dollars%*^










No comments:

Post a Comment