Sunday 2 November 2014

replaceFirst : Replace the first matched sequence

public String replaceFirst(String replacement)
Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string.

import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        System.out.println("Enter Regular Expression");
        regex = br.readLine();
        pattern = Pattern.compile(regex);
        
        while(true){
            try{
                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);

                String newStr = matcher.replaceFirst("dummy");
                System.out.println(newStr);
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Output
Enter Regular Expression
is
Enter the string
This is easy.. is it?
Thdummy is easy.. is it?



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment