정규식 Pattern.matches() , Matcher.matches() , Matcher.find()

황제낙엽 2010.01.19 17:05 조회 수 : 2474 추천:127

1. API 내용
boolean java.util.regex.Pattern.matches(String regex, CharSequence input)
Compiles the given regular expression and attempts to match the given input against it.

An invocation of this convenience method of the form

 Pattern.matches(regex, input);
behaves in exactly the same way as the expression
 Pattern.compile(regex).matcher(input).matches()
If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time.

Parameters:
regex The expression to be compiled
input The character sequence to be matched
Throws:
PatternSyntaxException If the expression's syntax is invalid

boolean java.util.regex.Matcher.matches()
Attempts to match the entire region against the pattern.

If the match succeeds then more information can be obtained via the start, end, and group methods.

Returns:
true if, and only if, the entire region sequence matches this matcher's pattern

boolean java.util.regex.Matcher.find()
Attempts to find the next subsequence of the input sequence that matches the pattern.

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

If the match succeeds then more information can be obtained via the start, end, and group methods.

Returns:
true if, and only if, a subsequence of the input sequence matches this matcher's pattern



대충 해석해 보면 Pattern.matches() 는 Matcher.matches() 와 같은 코드이고, Matcher.find() 와 구별되는 점은 다음과 같다.

matches() 함수는 입력된 문자열 전체에 대해서 매칭 검사를 실시하고, find() 함수는 입력된 문자열을 순회하면서 매칭 검사를 실시한다.

그말인 즉슨, matches() 함수를 쓰면 "abcd" 라는 문자열을 검사할때 "adcd" 가 모두 검사될 수 있도록 "abcd"라고 정규식을 작성해야지만

true 를 리턴하지만 find() 함수는 "abcd" 에서 "abc" 로 정규식을 작성해도 true 를 리턴할 수 있다는 야그다.

만일 matches() 에서 "abc" 로 정규식을 작성하면 false 를 리턴한다. "abc"를 찾아라가 아니라 "abc" 형태가 맞느냐? 라고 찾기 때문이다.

이를 비교한 샘플 프로그램이다.


 

·미리보기 | 소스복사·
  1. // -----------------------------------------------------------------------------   
  2. // RegDemoSun.java   
  3. // -----------------------------------------------------------------------------   
  4.   
  5. import java.util.regex.*;   
  6.   
  7. /**  
  8.  * -----------------------------------------------------------------------------  
  9.  * Used to provide an example of how to utilize the Java 2 Regular Expression  
  10.  * Implementation from Sun. It is important to note that a Regular Expression  
  11.  * implentation didn't appear in the Java SDK until version 1.4.  
  12.  *   
  13.  * Sun's implementation of its regular expression parser enables you to both  
  14.  * "find" and "match" character sequences against a particular pattern. Using  
  15.  * "find" enables the user to find matches in a string while "match" requires  
  16.  * an EXACT match of a regular expression.  
  17.  * -----------------------------------------------------------------------------  
  18.  */  
  19.     
  20. public class RegDemoSun {   
  21.   
  22.     private static void doRegDemo() {   
  23.   
  24.         String patternStrFull    = "^A[^b]-d+ - .+$";   
  25.         String patternStrPart    = "^A[^b]-d+ - ";   
  26.   
  27.         CharSequence inputStr1      = "AU-120 - Network Cable.";   
  28.         CharSequence inputStr2      = "au-120 - Network Cable.";   
  29.   
  30.         Pattern patternFull         = Pattern.compile(patternStrFull);   
  31.         Pattern patternPart         = Pattern.compile(patternStrPart);   
  32.         Pattern patternCaseInsFull  = Pattern.compile(patternStrFull, Pattern.CASE_INSENSITIVE);   
  33.         Pattern patternCaseInsPart  = Pattern.compile(patternStrPart, Pattern.CASE_INSENSITIVE);   
  34.            
  35.         Matcher matcher = null;   
  36.   
  37.         String matchStr     = " [ MATCHES ]  ";   
  38.         String noMatchStr   = " [ DOES NOT MATCH ]  ";   
  39.         String foundStr     = " [ FOUND ]  ";   
  40.         String noFoundStr   = " [ NOT FOUND ]  ";   
  41.         boolean found   = false;   
  42.            
  43.         System.out.println();   
  44.   
  45.   
  46.         // -------------------------------------------------------   
  47.         // Test 1 : (Case Sensitive / match() v.s. find() )   
  48.         // -------------------------------------------------------   
  49.   
  50.         System.out.println("Case sensitive :: matches() v.s. find()");   
  51.         System.out.println("---------------------------------------n");   
  52.            
  53.         matcher  = patternFull.matcher(inputStr1);   
  54.         found    = matcher.matches();   
  55.         System.out.println("Test 1: /" + inputStr1 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrFull + "/n");   
  56.   
  57.         matcher  = patternPart.matcher(inputStr1);   
  58.         found    = matcher.matches();   
  59.         System.out.println("Test 2: /" + inputStr1 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrPart + "/n");   
  60.   
  61.         matcher = patternFull.matcher(inputStr1);   
  62.         found = matcher.find();   
  63.         System.out.println("Test 3: /" + inputStr1 + "/" + (found  ?foundStr : noFoundStr) + "/" + patternStrFull + "/n");   
  64.   
  65.         matcher = patternPart.matcher(inputStr1);   
  66.         found = matcher.find();   
  67.         System.out.println("Test 4: /" + inputStr1 + "/" + (found  ?foundStr : noFoundStr) + "/" + patternStrPart + "/n");   
  68.   
  69.         matcher  = patternFull.matcher(inputStr2);   
  70.         found    = matcher.matches();   
  71.         System.out.println("Test 5: /" + inputStr2 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrFull + "/n");   
  72.   
  73.         matcher  = patternPart.matcher(inputStr2);   
  74.         found    = matcher.matches();   
  75.         System.out.println("Test 6: /" + inputStr2 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrPart + "/n");   
  76.   
  77.         matcher = patternFull.matcher(inputStr2);   
  78.         found = matcher.find();   
  79.         System.out.println("Test 7: /" + inputStr2 + "/" + (found  ?foundStr : noFoundStr) + "/" + patternStrFull + "/n");   
  80.   
  81.         matcher = patternPart.matcher(inputStr2);   
  82.         found = matcher.find();   
  83.         System.out.println("Test 8: /" + inputStr2 + "/" + (found  ?foundStr : noFoundStr) + "/" + patternStrPart + "/n");   
  84.   
  85.         System.out.println();   
  86.   
  87.   
  88.   
  89.         // -------------------------------------------------------   
  90.         // Test 2 : (Case Insensitive / match() v.s. find() )   
  91.         // -------------------------------------------------------   
  92.            
  93.         System.out.println("Case Insensitive :: matches() v.s. find()");   
  94.         System.out.println("-----------------------------------------n");   
  95.            
  96.         matcher  = patternCaseInsFull.matcher(inputStr1);   
  97.         found    = matcher.matches();   
  98.         System.out.println("Test 1: /" + inputStr1 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrFull + "/n");   
  99.   
  100.         matcher  = patternCaseInsPart.matcher(inputStr1);   
  101.         found    = matcher.matches();   
  102.         System.out.println("Test 2: /" + inputStr1 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrPart + "/n");   
  103.   
  104.         matcher = patternCaseInsFull.matcher(inputStr1);   
  105.         found = matcher.find();   
  106.         System.out.println("Test 3: /" + inputStr1 + "/" + (found  ?foundStr : noFoundStr) + "/" + patternStrFull + "/n");   
  107.   
  108.         matcher = patternCaseInsPart.matcher(inputStr1);   
  109.         found = matcher.find();   
  110.         System.out.println("Test 4: /" + inputStr1 + "/" + (found  ?foundStr : noFoundStr) + "/" + patternStrPart + "/n");   
  111.   
  112.         matcher  = patternCaseInsFull.matcher(inputStr2);   
  113.         found    = matcher.matches();   
  114.         System.out.println("Test 5: /" + inputStr2 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrFull + "/n");   
  115.   
  116.         matcher  = patternCaseInsPart.matcher(inputStr2);   
  117.         found    = matcher.matches();   
  118.         System.out.println("Test 6: /" + inputStr2 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrPart + "/n");   
  119.   
  120.         matcher = patternCaseInsFull.matcher(inputStr2);   
  121.         found = matcher.find();   
  122.         System.out.println("Test 7: /" + inputStr2 + "/" + (found  ?foundStr : noFoundStr) + "/" + patternStrFull + "/n");   
  123.   
  124.         matcher = patternCaseInsPart.matcher(inputStr2);   
  125.         found = matcher.find();   
  126.         System.out.println("Test 8: /" + inputStr2 + "/" + (found  ?foundStr : noFoundStr) + "/" + patternStrPart + "/n");   
  127.   
  128.         System.out.println();   
  129.   
  130.   
  131.         // ---------------------------------------------------------------   
  132.         // Test 3 : (Case Sensitive / Using convenience method matches() )   
  133.         // ---------------------------------------------------------------   
  134.            
  135.         System.out.println("Case Sensitive :: Using convenience method Pattern.matches(Pattern, CharSequence)");   
  136.         System.out.println("---------------------------------------------------------------------------------n");   
  137.   
  138.         found = Pattern.matches(patternStrFull, inputStr1);   
  139.         System.out.println("Test 1: /" + inputStr1 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrFull + "/n");   
  140.   
  141.         found = Pattern.matches(patternStrPart, inputStr1);   
  142.         System.out.println("Test 2: /" + inputStr1 + "/" + (found  ?matchStr : noMatchStr) + "/" + patternStrPart + "/n");    
  143.   
  144.         System.out.println();   
  145.   
  146.     }   
  147.   
  148.   
  149.     /**  
  150.      * Sole entry point to the class and application.  
  151.      * @param args Array of String arguments.  
  152.      */  
  153.     public static void main(String[] args) {   
  154.         doRegDemo();   
  155.     }   
  156.   
  157. }   


실행결과


Case sensitive :: matches() v.s. find()
---------------------------------------

Test 1: /AU-120 - Network Cable./ [ MATCHES ]  /^A[^b]-d+ - .+$/

Test 2: /AU-120 - Network Cable./ [ DOES NOT MATCH ]  /^A[^b]-d+ - /

Test 3: /AU-120 - Network Cable./ [ FOUND ]  /^A[^b]-d+ - .+$/

Test 4: /AU-120 - Network Cable./ [ FOUND ]  /^A[^b]-d+ - /

Test 5: /au-120 - Network Cable./ [ DOES NOT MATCH ]  /^A[^b]-d+ - .+$/

Test 6: /au-120 - Network Cable./ [ DOES NOT MATCH ]  /^A[^b]-d+ - /

Test 7: /au-120 - Network Cable./ [ NOT FOUND ]  /^A[^b]-d+ - .+$/

Test 8: /au-120 - Network Cable./ [ NOT FOUND ]  /^A[^b]-d+ - /


Case Insensitive :: matches() v.s. find()
-----------------------------------------

Test 1: /AU-120 - Network Cable./ [ MATCHES ]  /^A[^b]-d+ - .+$/

Test 2: /AU-120 - Network Cable./ [ DOES NOT MATCH ]  /^A[^b]-d+ - /

Test 3: /AU-120 - Network Cable./ [ FOUND ]  /^A[^b]-d+ - .+$/

Test 4: /AU-120 - Network Cable./ [ FOUND ]  /^A[^b]-d+ - /

Test 5: /au-120 - Network Cable./ [ MATCHES ]  /^A[^b]-d+ - .+$/

Test 6: /au-120 - Network Cable./ [ DOES NOT MATCH ]  /^A[^b]-d+ - /

Test 7: /au-120 - Network Cable./ [ FOUND ]  /^A[^b]-d+ - .+$/

Test 8: /au-120 - Network Cable./ [ FOUND ]  /^A[^b]-d+ - /


Case Sensitive :: Using convenience method Pattern.matches(Pattern, CharSequence)
---------------------------------------------------------------------------------

Test 1: /AU-120 - Network Cable./ [ MATCHES ]  /^A[^b]-d+ - .+$/

Test 2: /AU-120 - Network Cable./ [ DOES NOT MATCH ]  /^A[^b]-d+ - /


번호 제목 글쓴이 날짜 조회 수
347 java.util.Optional 에서의 map() 함수의 이해 황제낙엽 2026.06.24 666
346 linux(ubuntu) 의 jdk 21 이 설정된 환경에서 jdk 17 로 다운그레이드 절차 황제낙엽 2025.09.22 1532
345 [ChatGPT] javax.* 패키지와 jakarta.* 패키지의 혼합 사용 방안 황제낙엽 2025.04.15 2458
344 [ChatGPT] *.servlet.http.HttpServlet 클래스를 사용할 수 있는 주요 WAS 목록 황제낙엽 2025.04.14 2038
343 [ChatGPT] JDBC API에서 java.sql과 javax.sql 패키지의 차이점 황제낙엽 2025.01.31 2218
342 jakarta.servlet 패키지를 이용한 File Upload 구현 (2024.03.03, Servlet 5.0) 황제낙엽 2025.01.02 2310
341 [ChatGPT] Java EE가 Jakarta EE로 전환 황제낙엽 2025.01.01 2525
340 [ChatGPT] File.delete() 함수로 파일 삭제가 되지 않는 경우 황제낙엽 2024.12.10 2809
339 [ChatGPT] <jsp:include>에서 flush="true"를 설정시의 몇 가지 문제점 과 대안 황제낙엽 2024.07.19 2493
338 [Copilot] JSP, Servlet, web.xml, mysql 한글 설정 황제낙엽 2024.07.12 2555
337 Base64 클래스의 encode, decode 에서 URL-safe 황제낙엽 2024.07.10 2624
336 [Copilot] JSP 에서 다른 페이지를 현재 페이지에 포함시키는 문법 (include) 황제낙엽 2024.06.26 2570
335 Exception 출력에 대한 고찰 황제낙엽 2024.06.10 2198
334 google-auth-library-oauth2-http 라이브러리 다운로드 황제낙엽 2023.11.19 4025
333 firebase-admin-java 라이브러리 다운로드 (firebase admin sdk library) 황제낙엽 2023.11.19 2805
332 Enum 활용 (개인블로그, Effective Java) file 황제낙엽 2023.11.02 2759
331 Enum 활용 (우아한기술블로그) file 황제낙엽 2023.11.02 2790
330 servlet name 에 camel case 를 사용해서는 안되는 이유 황제낙엽 2023.10.24 2508
329 org.apache.commons.fileupload.servlet.ServletFileUpload 이용 예시 황제낙엽 2023.08.25 3336
328 ServletFileUpload.parseRequest() 실행 결과 리스트가 비어있는 오류 황제낙엽 2023.08.25 2935