go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  Regular expression with examples
 
Subject: Regular expression with examples
Author: Alex_Raj
Posted on: 08/07/2015 12:55:27 AM

A regular expression is a sequence of characters that define a pattern which is mainly used for:

  • finding match -- for a given string, is there any match found for the specific pattern?
  • validation/assertion -- for a given string, does the string fit the specific pattern?


    Example: Finding match -- the regular expression '[hc]at' matches 'cat' and 'hat' in string "The cat wears a hat."
        String regex = "[hc]at"; 
        String input = "The cat wears a hat.";
        System.out.println("Regex: " + regex);
        System.out.println("Input: " + input);
    	
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
    		
        boolean found = false;
        while (matcher.find()) {
            System.out.println("Found '" + matcher.group() + 
                               "' from " + matcher.start() + 
                               " to " + matcher.end());
            found = true;
        }
    
        if(!found)
            System.out.println("No match found!");
    


    output:
        Regex: [hc]at
        Input: The cat wears a hat.
        Found 'cat' from 4 to 7
        Found 'hat' from 16 to 19
    




    Example: Validation/assertion -- the input telephone number "415-555-1234" is good for the pattern '\d{3}-\d{3}-\d{4}'.
        String regex = "\\d{3}-\\d{3}-\\d{4}"; 
        String input = "415-555-1234";
        System.out.println("Regex: " + regex);
        System.out.println("Input: " + input);
      		
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
      		
        if (matcher.matches()) {
            System.out.println("Match!");
        } else {
            System.out.println("Does not match!");
        }
    


    output:
        Regex: \d{3}-\d{3}-\d{4}
        Input: 415-555-1234
        Match!
    


    Replies:


    References:

  •  


     
    Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
     
    Get your own forum today. It's easy and free.