Sunday, 2 November 2014

Split the input based on the pattern

Pattern class provides split method, which splits the given input sequence around matches of this pattern. Pattern class provides two variants of split method.

public String[] split(CharSequence input)
Splits the given input sequence around matches of this pattern.

import java.util.regex.*;

public class PatternMatch {
    public static void main(String args[]){     
        Pattern p = Pattern.compile(":");
        String text = "123:234:345:456:567:678:890";
        
        String s[] = p.split(text);
        
        for(int i=0; i<s.length; i++){
            System.out.println(s[i]);
        }
    }
}

Output
123
234
345
456
567
678
890

public String[] split(CharSequence input, int limit)
Splits the given input sequence around matches of this pattern. The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

If the limit 'n' is greater than zero, then the pattern will be applied at most n - 1 times.

If limit is zero or non-positive then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

import java.util.regex.*;

public class PatternMatch {
    public static void main(String args[]){     
        Pattern p = Pattern.compile(":");
        String text = "123:234:345:456:567:678:890";

        for(int j=0; j<6; j++){
            System.out.println("--------------------");
            System.out.println("For the split count " + j);     
            String s[] = p.split(text, j);
            for(int i=0; i<s.length; i++){
                System.out.println(s[i]);
            }
        }
    }
}

Output
--------------------
For the split count 0
123
234
345
456
567
678
890
--------------------
For the split count 1
123:234:345:456:567:678:890
--------------------
For the split count 2
123
234:345:456:567:678:890
--------------------
For the split count 3
123
234
345:456:567:678:890
--------------------
For the split count 4
123
234
345
456:567:678:890
--------------------
For the split count 5
123
234
345
456
567:678:890



 

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment