Tuesday 19 December 2017

How to use split method of pattern class to split the text into multiple Strings | Java Regex


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=UciRkYHFykI&list=UUhwKlOVR041tngjerWxVccw

RegexDemo.java


import java.util.regex.Pattern;

/**
 *
 * To split a text into multiple strings based on a delimiter (Here delimiter
 * would be specified using regex), we can use Pattern.split() method.
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {
        String inputCharSeq = "Peter_Welcome_to_india";
       
        // Pattern for delimiter
        String regex = "_";
       
        Pattern pattern = Pattern.compile(regex);
        /*
         * Returns:The array of strings computed by splitting the input around
         * matches of this pattern.
         */

        String[] stringArray = pattern.split(inputCharSeq);
       
        for (String str : stringArray)
        {
            System.out.println(str);
        }
        System.out.println("Number of split strings: " + stringArray.length);
    }

}

Output

Peter
Welcome
to
india
Number of split strings: 4

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/RegexDemo_split.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/RegexDemo_split

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/ef02c9011c18b0aa670526ba89cc11f493b9b854/BasicJava/RegexDemo_split/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment