Tuesday, December 23, 2014

Replace all occourances of a string and each word in Uppercase in java



Replace all occourances 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.replaceAll("Java");
      System.out.println("String after replacing 1st Match: "+tmp);
   }
             }

Make first letter of each word in Uppercase

import java.util.regex.Matcher;
import java.util.regex.Pattern;
            public class Main 
{
   public static void main(String[] args) 
  {
      String str = "this is a java test";
      System.out.println(str);
      StringBuffer stringbf = new StringBuffer();
      Matcher m = Pattern.compile("([a-z])([a-z]*)",
      Pattern.case_insensitive).matcher(str);
      while (m.find()) 
      {
         m.appendReplacement(stringbf, 
         m.group(1).toUpperCase() + m.group(2).toLowerCase());
      }
      System.out.println(m.appendTail(stringbf).toString());
   }
}

No comments:

Post a Comment