Sunday 6 October 2013

Regular Expressions with java.util.regex.*

A regular expression defines a patter for a String. Regular expressions are extremely useful in extracting information from text such as code, log files, spreadsheets, or even documents.The first thing to recognize when using regular expressions is that everything is essentially a character, and we are writing patterns to match a specific sequence of characters.

"A regular expression is a kind of pattern that can be applied to Strings."

"A regular expression either matches the text or part of the text, or it fails to match." 
"Regular expressions are extremely useful for manipulating text"


Java has a regular expression package, java.util.regex.

Now Do it,
  1. create Object of Pattern Class.

    Pattern p = Pattern.compile("[a-z]+");
  2. create a matcher for a specific piece of text by passing a String to a Pattern Object.

    Matcher m = p.matcher("Now is the time");
  3. Now that we have a matcher m,
    •  m.matches() returns true  if the pattern matches the entire text string, and false otherwise
    • m.lookingAt() returns true if the pattern matches at the beginning of the text string, and false otherwise
    • m.find() returns true if the pattern matches any part of the text string, and false otherwise
    • If called again, m.find() will start searching from where the last match was found
    • m.find() will return true for as many matches as there are in the string; after that, it will return false
    •  When m.find()  returns false, matcher m will be reset to the beginning of the text string (and may be used again)
    • After a successful match, m.start() will return the index of the first character matched
    • After a successful match, m.end() will return the index of the last character matched, plus one
    • If no match was attempted, or if the match was unsuccessful, m.start() and m.end() will throw an IllegalStateException
    • m.replaceFirst(replacement) returns a new String where the first substring matched by the pattern has been replaced by replacement
    • m.replaceAll(replacement) returns a new String where every substring matched by the pattern has been replaced by replacement
    • m.find(startIndex) looks for the next pattern match, starting at the specified index
    • m.reset() resets this matcher
    • m.reset(newText) resets this matcher and gives it new text to examine (which may be a String, StringBuffer, or CharBuffer)
     
 Patterns Matches :

  








Breaking down:











 Regular Expression Cheat Sheet

No comments:

Post a Comment