KickJava   Java API By Example, From Geeks To Geeks.

Java > Java SE, EE, ME > java > util > regex > Matcher

java.util.regex
Class Matcher

java.lang.Object
  extended by java.util.regex.Matcher
All Implemented Interfaces:
MatchResult
See Also:
Top Examples, Source Code, reset(CharSequence), reset(), IllegalStateException, replaceAll, appendTail, appendReplacement, useTransparentBounds, useAnchoringBounds, regionEnd, regionStart, region, find, lookingAt, matches, matcher, character sequence

public Matcher appendReplacement(StringBuffer sb,
                                 String replacement)
See Also:
IndexOutOfBoundsException, IllegalStateException, find, appendTail, group, end(), start()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1231]Use pattern matcher to replace a string
By Anonymous on 2005/03/29 08:27:37  Rate
/* 
  * This code writes "One dog, two dogs in the yard." 
  * to the standard-output stream: 
  */
 
  
  
 // Create a pattern to match cat 
 Pattern p = Pattern.compile ( "cat" ) ; 
 // Create a matcher with an input string 
 Matcher m = p.matcher ( "one cat," + 
          " two cats in the yard" ) ; 
 StringBuffer sb = new StringBuffer (  ) ; 
 boolean result = m.find (  ) ; 
 // Loop through and create a new String  
 // with the replacements 
 while ( result )   {  
     m.appendReplacement ( sb, "dog" ) ; 
     result = m.find (  ) ; 
  }  
 // Add the last segment of input to  
 // the new String 
 m.appendTail ( sb ) ; 
 System.out.println ( sb.toString (  )  ) ; 
 


[1781]match special string
By Anonymous on 2006/06/23 01:45:41  Rate
public static void main ( String args [  ]  )  {  
     String prex="default"; 
     Pattern p = Pattern.compile ( "^"+prex+" ( \\d+ ) $" ) ; 
     String line="default0001"; 
     Matcher m = p.matcher ( line ) ;  
         if  ( m.find (  )  == true )  //line matches the above pattern ?  
          {   
           System.out.println ( m.group ( 1 )  ) ; // [ A-Z ]  [ ^\\s ] +  
          } else {  
           System.out.println ( "the line is not matched!" ) ;   
          }    
    } 


public StringBuffer appendTail(StringBuffer sb)
See Also:
appendReplacement
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public int end()
See Also:
IllegalStateException, MatchResult
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public int end(int group)
See Also:
IndexOutOfBoundsException, IllegalStateException, MatchResult
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean find()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1279]Problem with mathcher.find
By Anonymous on 2005/04/24 09:41:02  Rate
my regex is "\\W*" 
 my string is se 
  
  
 i do mathcher.find (  )  -this one return false. 
  
  
 Why?


[1525]_
By Mark on 2005/08/30 06:48:28  Rate
\W    = A non-word character:  [ ^\w ] 

public boolean find(int start)
See Also:
IndexOutOfBoundsException, find()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public String group()
See Also:
IllegalStateException, MatchResult
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public String group(int group)
See Also:
IndexOutOfBoundsException, IllegalStateException, MatchResult
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public int groupCount()
See Also:
MatchResult
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean hasAnchoringBounds()
See Also:
useAnchoringBounds(boolean)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean hasTransparentBounds()
See Also:
useTransparentBounds(boolean)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean hitEnd()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean lookingAt()
See Also:
matches
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1924]Difference between the matches and lookingAt Methods
By Anonymous on 2007/08/15 11:24:33  Rate
The matches and lookingAt methods both attempt to match an input sequence against a pattern. The difference, however, is that matches requires the entire input sequence to be matched, while lookingAt does not. Both methods always start at the beginning of the input string.  
  
  
     import java.util.regex.Pattern; 
     import java.util.regex.Matcher; 
  
  
     public class MatchesLooking  {  
  
  
         private static final String REGEX = "foo"; 
         private static final String INPUT = "fooooooooooooooooo"; 
         private static Pattern pattern; 
         private static Matcher matcher; 
  
  
         public static void main ( String [  ]  args )   {  
         
           // Initialize 
             pattern = Pattern.compile ( REGEX ) ; 
             matcher = pattern.matcher ( INPUT ) ; 
  
  
             System.out.println ( "Current REGEX is: "+REGEX ) ; 
             System.out.println ( "Current INPUT is: "+INPUT ) ; 
  
  
             System.out.println ( "lookingAt (  ) : "+matcher.lookingAt (  )  ) ; 
             System.out.println ( "matches (  ) : "+matcher.matches (  )  ) ; 
  
  
          }  
      }  
  
  
  
     Current REGEX is: foo 
     Current INPUT is: fooooooooooooooooo 
     lookingAt (  ) : true 
     matches (  ) : false


public boolean matches()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[42]Parse the hosts file and retrive the IP address using pattern match
By grmnn { at } web { dot } de on 2003/08/31 21:13:14  Rate
import java.io.BufferedReader; 
 import java.io.FileReader; 
 import java.io.IOException; 
 import java.util.Vector; 
 import java.util.regex.Matcher; 
 import java.util.regex.Pattern; 
  
  
  
 public class hostTable extends Vector 
  {  
   
    public hostTable (  )  throws IOException 
     {  
      BufferedReader bufInput = null;  
        FileReader input = new FileReader ( "C:\\WINNT\\system32\\drivers\\etc\\hosts" ) ; 
        bufInput = new BufferedReader ( input ) ; 
                 
          Pattern p = Pattern.compile ( "^\\s?\\d+\\.\\d+\\.\\d+\\.\\d+\\s+ (  [ A-Z ]  [ ^\\s ] + ) \\s.*$" ) ; 
     /*maybe a blank, then an IP-adress,followed by blank ( s ) ,followed by a hostname that starts with A-Z,followed by blank ( s )  and maybe anything else*/ 
      
     try  
        {  
        String line = bufInput.readLine (  ) ; 
        while  (  line != null  )   
              {    
          
         Matcher m = p.matcher ( line ) ;  
         if  ( m.find (  )  == true )    //line matches the above pattern ? 
            {  
           String sys=m.group ( 1 ) ; // [ A-Z ]  [ ^\\s ] + 
           this.add ( sys ) ; 
  
  
                }  
             line = bufInput.readLine (  ) ;   
              }  
  
  
        bufInput.close (  ) ; 
  
  
        }  
     catch  ( Exception e )   {  e.printStackTrace (  ) ;  }         
    
     }  
  
  
  }  
 


[920]Check pattern
By kalyan on 2004/09/23 05:22:45  Rate
public static boolean chkpattern ( String _storetokens )   
      {  
  
  
       Pattern p = Pattern.compile ( "//" ) ; 
        
       Matcher m = p.matcher ( _storetokens ) ; 
        
       if   ( m.matches (  )  == true )  
        {  
       return false; 
        }  
       else 
        {   
       return true; 
        }      
 


public Pattern pattern()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static String quoteReplacement(String s)
See Also:
Matcher
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Matcher region(int start,
                      int end)
See Also:
IndexOutOfBoundsException, useAnchoringBounds, useTransparentBounds
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public int regionEnd()
See Also:
regionStart
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public int regionStart()
See Also:
regionEnd
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public String replaceAll(String replacement)
See Also:
appendReplacement
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[533]Replace letter tag
By Anonymous on 2004/07/05 06:28:20  Rate
  public String getreplaceLetterTags ( String string )  
    {  
      
     java.util.Date utilDate =  ( java.util.Date ) this.getSearchBean (  ) .getDateTo (  ) ; 
     str = replaceLetterTag ( String string ) ; 
      
     if  ( this.getDCN (  ) .getLetterBody (  )  != null )  
      {  
     return 
      
      
     str = str.replaceAll ( " < dcn:CurrentDate/ > ", "DCNBean.getSubmitterCompany (  ) .getDate (  ) " )  
     str = str.replaceAll ( " < dcn:CompanyName/ > ", "DCNBean.getSubmitterCompany (  ) .getName (  ) " )  
     str = str.replaceAll ( " < dcn:CompanyAddress1/ > ", "DCNBean.getSubmitterCompany (  ) .getAddress1 (  ) " )  
     str = str.replaceAll ( " < dcn:CompanyAddress2/ > ", "DCNBean.getSubmitterCompany (  ) .getAddress2 (  ) " )  
     str = str.replaceAll ( " < dcn:CompanyCity/ > ", "DCNBean.getSubmitterCompany (  ) .getCity (  ) " )  
     str = str.replaceAll ( " < dcn:CompanyState/ > ", "DCNBean.getSubmitterCompany (  ) .getState (  ) " )  
     str = str.replaceAll ( " < dcn:CompanyZip/ > ", "DCNBean.getSubmitterCompany (  ) .getZip (  ) " )  
     str = str.replaceAll ( " < dcn:AuthorName/ > ", "DCNBean.getSubmitterPOC.getFullName (  ) " )  
     str = str.replaceAll ( " < dcn:CoverLetterDate/ > ", "DCNBean.getCoverLetterDate (  ) " )  
     str = str.replaceAll ( " < dcn:DCNNumber/ > ", "DCNbean.getDCNNumber (  ) " ) ; 
      
      }  
      
     else 
          {  
           return ""; 
          }  
    } 


[1925]Replace text that matches any regular expression.
By Anonymous on 2007/08/15 11:28:10  Rate
The API for this method states that "given the regular expression a*b, the input aabfooaabfooabfoob, and the replacement string -, an invocation of this method on a matcher for that expression would yield the string -foo-foo-foo-." 
  
  
     import java.util.regex.Pattern; 
     import java.util.regex.Matcher; 
       
     public class ReplaceDemo2  {  
       
         private static String REGEX = "a*b"; 
         private static String INPUT = "aabfooaabfooabfoob"; 
         private static String REPLACE = "-"; 
       
         public static void main ( String [  ]  args )   {  
             Pattern p = Pattern.compile ( REGEX ) ; 
             Matcher m = p.matcher ( INPUT ) ; // get a matcher object 
             INPUT = m.replaceAll ( REPLACE ) ; 
             System.out.println ( INPUT ) ; 
          }  
      }  
  
  
  
     OUTPUT: -foo-foo-foo-


[1926]Alternative to replaceAll
By Anonymous on 2007/08/15 11:29:10  Rate
The Matcher class also provides appendReplacement and appendTail methods for text replacement. The following example uses these two methods to achieve the same effect as replaceAll. 
  
  
     import java.util.regex.Pattern; 
     import java.util.regex.Matcher; 
  
  
     public class RegexDemo  {  
       
         private static String REGEX = "a*b"; 
         private static String INPUT = "aabfooaabfooabfoob"; 
         private static String REPLACE = "-"; 
       
         public static void main ( String [  ]  args )   {  
             Pattern p = Pattern.compile ( REGEX ) ; 
             Matcher m = p.matcher ( INPUT ) ; // get a matcher object 
             StringBuffer sb = new StringBuffer (  ) ; 
             while ( m.find (  )  )  {  
                 m.appendReplacement ( sb,REPLACE ) ; 
              }  
             m.appendTail ( sb ) ; 
             System.out.println ( sb.toString (  )  ) ; 
          }  
      }  
  
  
  
  
     OUTPUT: -foo-foo-foo-


public String replaceFirst(String replacement)
See Also:
NullPointerException, appendReplacement
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean requireEnd()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Matcher reset()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Matcher reset(CharSequence input)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public int start()
See Also:
IllegalStateException, MatchResult
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1923]Counts the number of times a word appears using RegEx
By Anonymous on 2007/08/15 11:22:52  Rate
//Counts the number of times the word "dog" appears in the input string. 
  
  
    import java.util.regex.Pattern; 
     import java.util.regex.Matcher; 
  
  
     public class MatcherDemo  {  
  
  
         private static final String REGEX = "\\bdog\\b"; 
         private static final String INPUT = "dog dog dog doggie dogg"; 
  
  
         public static void main ( String [  ]  args )   {  
            Pattern p = Pattern.compile ( REGEX ) ; 
            Matcher m = p.matcher ( INPUT ) ; // get a matcher object 
            int count = 0; 
            while ( m.find (  )  )   {  
                count++; 
                System.out.println ( "Match number "+count ) ; 
                System.out.println ( "start (  ) : "+m.start (  )  ) ; 
                System.out.println ( "end (  ) : "+m.end (  )  ) ; 
             }  
          }  
      }  
  
  
  
     OUTPUT: 
  
  
     Match number 1 
     start (  ) : 0 
     end (  ) : 3 
     Match number 2 
     start (  ) : 4 
     end (  ) : 7 
     Match number 3 
     start (  ) : 8 
     end (  ) : 11 
  
  
 You can see that this example uses word boundaries to ensure that the letters "d" "o" "g" are not merely a substring in a longer word. It also gives some useful information about where in the input string the match has occurred. The start method returns the start index of the subsequence captured by the given group during the previous match operation, and end returns the index of the last character matched, plus one. 
 


public int start(int group)
See Also:
IndexOutOfBoundsException, IllegalStateException, MatchResult
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public MatchResult toMatchResult()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public String toString()
See Also:
Object
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Matcher useAnchoringBounds(boolean b)
See Also:
hasAnchoringBounds()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Matcher usePattern(Pattern newPattern)
See Also:
IllegalArgumentException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Matcher useTransparentBounds(boolean b)
See Also:
hasTransparentBounds()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  

Popular Tags