Pacific-Design.com

    
Home Index

1. Algorithms

2. Regex

+ Replace

Algorithms / Regex /

Regex.java

Regex.java

public class Regex {

    public static void main(String[] args) {

        String string = "Hello Kevin, how are you!";

        /*-------------------------String Matching -------------------------------------------*/
        //--- Starts with ---//
        if(string.startsWith("Hello Kevin")) System.out.println("Hello Kevin");

        //--- Ends with ---//
        if(string.endsWith("how are you!")) System.out.println("how are you!");

        //--- Match Anywhere ---//
        if(string.contains("Kevin")) System.out.println("Kevin");
        

        //--- Get Position Matched ---//
        if(string.indexOf("Kevin") > 0) System.out.println("Kevin="+string.indexOf("Kevin"));

        System.out.println("\n---------------------------\n");
        
        /*------------------------- Regular Expresions ----------------------------------------*/
        // Starts with ignore case ---//
        if(string.matches("(?i)Hello Kevin,.*")) System.out.println("Hello Kevin,");

        //--- Ends with ignore case ---//
        if(string.matches("(?i).*, how are you!")) System.out.println(", how are you!");

        //--- Match Anywhere ignore case ---//
        if(string.matches("(?i).*Kevin,.*")) System.out.println("Kevin,");
        
        //--- Match Anywhere ---//
        if(string.matches(".*Kevin, how.*")) System.out.println("Kevin, how");

    }
    /*--------------------------------------------------------------------------------------------*/

}

Output

Hello Kevin
how are you!
Kevin
Kevin=6

---------------------------

Hello Kevin,
, how are you!
Kevin,
Kevin, how