정규식 Methods of the Matcher Class

황제낙엽 2010.01.19 17:53 조회 수 : 120 추천:113

sitelink1  
sitelink2  
sitelink3  
sitelink4  
sitelink5  
sitelink6  
http://blog.naver.com/youmasan?Redirect=Log&logNo=130028771529http://java.sun.com/docs/books/tutorial/essential/regex/matcher.html
Methods of the Matcher Class

This section describes some additional useful methods of the Matcher class. For convenience, the methods listed below are grouped according to functionality.

이섹션은 Matcher클래스의 일부 추가된 유용한 메소드를 성명한다. 아래에 리스트된 메소드드는 기능에 따라 구룹되어 진다. 

Index Methods

Index methods provide useful index values that show precisely where the match was found in the input string:

인덱스 메소드는 유용한 인덱스 값을 제공하는데, 그 값은 입력 문자와 그 매치가 어디에서 발견되었는지 명확하게 보여준다.

  • public int start(): Returns the start index of the previous match.  이전 매치의 시작 인덱스 리턴
  • public int start(int group): Returns the start index of the subsequence captured by the given group during the previous match operation. 앞의 매치 연산을 하능 동안 주어진 그룹에 의해, 캡처된 하위시퀀스의 시작 인덱스를 리턴한다.
  • public int end(): Returns the offset after the last character matched. 매친된 마지막 문자 다음의 위치를 리턴한다.
  • public int end(int group): Returns the offset after the last character of the subsequence captured by the given group during the previous match operation. 이전 매치연산 동안 주어진 캡처에 의한  하위시퀀스의 마지막 문자 다음의 위치를 리턴한다.

Study Methods

Study methods review the input string and return a boolean indicating whether or not the pattern is found.

스터디 메소드는 입력 문자열을 재검토하고, 패턴이 발견되었는지, 아닌지를 나타내는 불린값을 리턴한다.

  • public boolean lookingAt(): Attempts to match the input sequence, starting at the beginning of the region, against the pattern.  패턴에 대해 입력시퀀스에 매치를 시도하라.시작점에서 시작하는,
  • public boolean find(): Attempts to find the next subsequence of the input sequence that matches the pattern.  패턴에 매치하는 입력 시권스의 다음 하위시퀀스를 찾는것을 시도하라.
  • public boolean find(int start): Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.  이 매처를 리셋하고, 패턴에 매치하는 입력 시퀀스의 다음 하위시퀀스를 찾는것을 시도하라. 특별한 위치에서 시작하는,
  • public boolean matches(): Attempts to match the entire region against the pattern.  패턴에 대해 전체 지역을 매치하라.

Replacement Methods

Replacement methods are useful methods for replacing text in an input string.

교환 메소드는 입력 문자열에서 문자 교환을 위한 유용한 메소드다.

  • public Matcher appendReplacement(StringBuffer sb, String replacement): Implements a non-terminal append-and-replace step.  끝이 아닌 추가/교체 단계를 수행하라.
  • public StringBuffer appendTail(StringBuffer sb): Implements a terminal append-and-replace step. 끝의 추가/교체 단계를 수행하라
  • public String replaceAll(String replacement): Replaces every subsequence of the input sequence that matches the pattern with the given replacement string. 패턴에 매치하는 입력 시퀀스의 모든 하위시퀀스를 주어진 교체문자로 교체하라.
  • public String replaceFirst(String replacement): Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string. 패턴에 매치하는 입력문자의 첫번째 하위 문자를 주어준 교체 문자로 교체하라
  • public static String quoteReplacement(String s): Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ('') and dollar signs ('$') will be given no special meaning. 명세된 String을 위한 문자상의 교체String를 리턴하라. 이메소드는 Matcher클래스의 appendReplacement 메소드에서 문자상의 교체로써, 작업할 문자열을 만들어 낸다. 만들어진 문자열은 문자상의 시퀀스로써, 다루어진 s의 문자열의 시퀀스와 매치될 것이다. 와 $는 특별한 의미를 갖지 않는다.

Using the start and end Methods

Here's an example, MatcherDemo.java, that counts the number of times the word "dog" appears in the input string.

입력문자열에서 "dog" 단어가 나타나는 횟수를 계산하는 예제가 있다.

·미리보기 | 소스복사·
  1. import java.util.regex.Pattern;   
  2. import java.util.regex.Matcher;   
  3.   
  4. public class MatcherDemo {   
  5.   
  6.     private static final String REGEX = "bdogb";   
  7.     private static final String INPUT = "dog dog dog doggie dogg";   
  8.   
  9.     public static void main(String[] args) {   
  10.        Pattern p = Pattern.compile(REGEX);   
  11.        Matcher m = p.matcher(INPUT); // get a matcher object   
  12.        int count = 0;   
  13.        while(m.find()) {   
  14.            count++;   
  15.            System.out.println("Match number "+count);   
  16.            System.out.println("start(): "+m.start());   
  17.            System.out.println("end(): "+m.end());   
  18.        }   
  19.     }   
  20. }   
  21.   
  22.   
  23. OUTPUT:   
  24.   
  25. Match number 1   
  26. start(): 0   
  27. end(): 3   
  28. Match number 2   
  29. start(): 4   
  30. end(): 7   
  31. Match number 3   
  32. start(): 8   
  33. 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. 이 예제가  d,o,g문자들이 더 긴 단어의 하위 문자들이 아니라는것을 입증하기 위해, 단어 경계를 사용하는것을 볼수 있다.  start메소드는 이전 매치 연산동안 주언진 그룹에 의해 캨처된 하위 시퀀스의 시작 인덱스를 리턴한다. 그맇고 end 는 매치된 마지막 문자의 인덱스 + 1 값을 리턴한다.

Using the matches and lookingAt Methods

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. Here's the full code, MatchesLooking.java:

matche와 lookingAt메소드 모두 패턴에 대해, 입력 시퀀스와 매치하는것을 시도한다. 다른점은 matche는 매치되는 입력 시퀀스 전체를 요구하지만, lookingAt은 그렇지 않다. 두 메소드 모두 입력 문자열의 시작점에서 시작한다.

·미리보기 | 소스복사·
  1. import java.util.regex.Pattern;   
  2. import java.util.regex.Matcher;   
  3.   
  4. public class MatchesLooking {   
  5.   
  6.     private static final String REGEX = "foo";   
  7.     private static final String INPUT = "fooooooooooooooooo";   
  8.     private static Pattern pattern;   
  9.     private static Matcher matcher;   
  10.   
  11.     public static void main(String[] args) {   
  12.       
  13.       // Initialize   
  14.         pattern = Pattern.compile(REGEX);   
  15.         matcher = pattern.matcher(INPUT);   
  16.   
  17.         System.out.println("Current REGEX is: "+REGEX);   
  18.         System.out.println("Current INPUT is: "+INPUT);   
  19.   
  20.         System.out.println("lookingAt(): "+matcher.lookingAt());   
  21.         System.out.println("matches(): "+matcher.matches());   
  22.   
  23.     }   
  24. }   
  25.   
  26.   
  27. Current REGEX is: foo   
  28. Current INPUT is: fooooooooooooooooo   
  29. lookingAt(): true  
  30. matches(): false  

Using replaceFirst(String) and replaceAll(String)

The replaceFirst and replaceAll methods replace text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurences. Here's the ReplaceDemo.java code:

replaceFirst 와 replaceAll 메소드는 주어진 정규식과 매치하는 텍스트를 교체한다. 메소드의 이름이 말해주는것 처럼, replaceFirst는 처음 발생한 것과 교체하고, replaceAll는 모든 발생을 교체한다.

·미리보기 | 소스복사·
  1. import java.util.regex.Pattern;    
  2. import java.util.regex.Matcher;   
  3.   
  4. public class ReplaceDemo {   
  5.     
  6.     private static String REGEX = "dog";   
  7.     private static String INPUT = "The dog says meow. All dogs say meow.";   
  8.     private static String REPLACE = "cat";   
  9.     
  10.     public static void main(String[] args) {   
  11.         Pattern p = Pattern.compile(REGEX);   
  12.         Matcher m = p.matcher(INPUT); // get a matcher object   
  13.         INPUT = m.replaceAll(REPLACE);   
  14.         System.out.println(INPUT);   
  15.     }   
  16. }   
  17.   
  18.   
  19. OUTPUT: The cat says meow. All cats say meow.   
  20.   
In this first version, all occurrences of dog are replaced with cat. But why stop here? Rather than replace a simple literal like dog, you can replace text that matches any regular expression. 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-."

Here's the ReplaceDemo2.java code:

이 처음 버전에서, dog의 모든 발생은 cat로 대체된다. 그런데 왜 여기는 멈췄는가? dog처럼 간단한 문자열을  교체하는것 보다, 어떤 정규식과 매치하는 텍스트를 교체할수 있다. 이 메소드의  API는 주어진 정규식 a*b, aabfooaabfooabfoob 입력, 그리고 교체문자 -, 그 정규식을 위한 매처에서 이 메소드의 호출은 -foo-foo-foo-를 나타낼것이다. 라고 말한다.

·미리보기 | 소스복사·
  1. import java.util.regex.Pattern;   
  2. import java.util.regex.Matcher;   
  3.     
  4. public class ReplaceDemo2 {   
  5.     
  6.     private static String REGEX = "a*b";   
  7.     private static String INPUT = "aabfooaabfooabfoob";   
  8.     private static String REPLACE = "-";   
  9.     
  10.     public static void main(String[] args) {   
  11.         Pattern p = Pattern.compile(REGEX);   
  12.         Matcher m = p.matcher(INPUT); // get a matcher object   
  13.         INPUT = m.replaceAll(REPLACE);   
  14.         System.out.println(INPUT);   
  15.     }   
  16. }   
  17.   
  18.   
  19. OUTPUT: -foo-foo-foo-  
To replace only the first occurrence of the pattern, simply call replaceFirst instead of replaceAll. It accepts the same parameter.  단지 패턴의 처음 발생을 교체하기 위해, replaceAll대신에 replaceFirst를 호출할수 있다. 같은 파라미터를 허용한다.

Using appendReplacement(StringBuffer,String) and appendTail(StringBuffer)

The Matcher class also provides appendReplacement and appendTail methods for text replacement. The following example, RegexDemo.java, uses these two methods to achieve the same effect as replaceAll.

텍스트 교체를 위해, Matcher클래스는 appendReplacement와 appendTail메소드를 제공한다. 다음예제는, replaceAll과 같은 효과를 내기 위해 사용한다.

·미리보기 | 소스복사·
  1. import java.util.regex.Pattern;   
  2. import java.util.regex.Matcher;   
  3.   
  4. public class RegexDemo {   
  5.     
  6.     private static String REGEX = "a*b";   
  7.     private static String INPUT = "aabfooaabfooabfoob";   
  8.     private static String REPLACE = "-";   
  9.     
  10.     public static void main(String[] args) {   
  11.         Pattern p = Pattern.compile(REGEX);   
  12.         Matcher m = p.matcher(INPUT); // get a matcher object   
  13.         StringBuffer sb = new StringBuffer();   
  14.         while(m.find()){   
  15.             m.appendReplacement(sb,REPLACE);   
  16.         }   
  17.         m.appendTail(sb);   
  18.         System.out.println(sb.toString());   
  19.     }   
  20. }   
  21.   
  22.   
  23.   
  24. OUTPUT: -foo-foo-foo-  

Matcher Method Equivalents in java.lang.String

For convenience, the String class mimics a couple of Matcher methods as well:
  • public String replaceFirst(String regex, String replacement): Replaces the first substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceFirst(regex, repl) yields exactly the same result as the expression Pattern.compile(regex).matcher(str).replaceFirst(repl) 주어진 정규식에 매치하는 이 문자열의 첫번째 하위문자열을 주어진 replacement로 교체하라. Pattern.compile(regex).matcher(str).repaceFirst(repl)과 같은 표현이다. 

     

  • public String replaceAll(String regex, String replacement): Replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression Pattern.compile(regex).matcher(str).replaceAll(repl) 주어진 정규식에 매치하는 이 문자열의 각 하위 문자열을 주어진 replacement로 교체하라. Pattern.compile(regex).matcher(str).replaceAll(repl)과 같은 결과를 낸다.

     



번호 제목 글쓴이 날짜 조회 수
171 메모리 유출과 약한 참조 황제낙엽 2010.01.26 616
» Methods of the Matcher Class 황제낙엽 2010.01.19 120
169 Pattern.matches() , Matcher.matches() , Matcher.find() file 황제낙엽 2010.01.19 105
168 java.lang.IllegalArgumentException 황제낙엽 2010.01.18 130512
167 org.apache.commons.fileupload.servlet.ServletFileUpload 를 이용한 파일 업로드 file 황제낙엽 2009.11.19 129
166 Error reading tld listeners java.lang.NullPointerException 황제낙엽 2009.10.14 67
165 Cannot find the tag library descriptor for “http://java.sun.com/jsp/jstl/core 황제낙엽 2009.10.14 1006
164 Transfer-Encoding: chunked VS Content-Length 황제낙엽 2009.09.17 154
163 서블릿 응답 헤더(Response Header) 황제낙엽 2009.09.17 80
162 같은 문자열인데도 정규식에서 해당 문자열을 파싱하지 못하는 경우 황제낙엽 2009.08.08 39
161 MultipartRequest (cos.jar)와 서블릿을 이용한 업로드 file 황제낙엽 2009.06.19 384
160 [대용량 파일 업로드] multipart form parser - http file upload, database 저장 java class 연재2 file 황제낙엽 2009.06.19 1831
159 [대용량 파일 업로드] multipart form parser - http file upload 기능 java class 연재1 file 황제낙엽 2009.06.19 1436
158 [reflection/리플렉션] Class.forName 황제낙엽 2009.05.27 101
157 문자열 내의 공백을 제거하는 간단한 정규식 황제낙엽 2009.05.20 88
156 문자열에서 특수 문자 (Escape Sequence) 처리 file 황제낙엽 2009.02.20 1322
155 정규표현식을 사용하는 String클래스의 replaceAll() 함수 개량 황제낙엽 2009.02.09 219
154 File 복사 함수 황제낙엽 2009.02.08 31
153 JSP session 정보 얻기 황제낙엽 2009.01.21 127
152 서버상의 로컬경로 (실제경로) 관련 환경변수 황제낙엽 2009.01.21 339