Regular Expression 정규표현식(4) Java Pattern, Matcher Class
Java RegEx 매칭활용
import java.io.Console; import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexTestHarness { public static void main(String[] args){ Console console = System.console(); if (console == null) { System.err.println("No console."); System.exit(1); } while (true) { Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: ")); Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: ")); boolean found = false; while (matcher.find()) { console.format("I found the text" + " \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end()); found = true; } if(!found){ console.format("No match found.%n"); } } } }
Pattern Class
1. Pattern p = Pattern.compile(String RegEx표현, Pattern.CASE_INSENSITIVE);
Pattern p = Pattern.compile("(?i)foo");
RegEx 표현을 패턴 객체화합니다.
그 때 대소문자 구분하지 않는다고 플래그를 달 수 있습니다.
요건 간단하게 Embedded Flag Expressions 를 사용해도 됩니다.
2. Matcher matcher = p.matcher(String inputSource);
InputSource 에서 pattern 에 매칭시킬수 있는 Matcher 클래스 (도구) 를 생성한다.
3. String[] items = p.split(String InputSource);
Pattern 으로 InputSource 를 구분해서 String 배열에 넣습니다.
Matcher Class
1. Boolean matchingYN = matcher.find();
matcher 의 매칭결과가 있는지 YN 으로 표시합니다.
2. matcher.start(); matcher.end();
이전 매칭결과의 Start Index, End Index 를 구합니다.
3. String previousMatching = matcher.group();
이전 매칭결과의 매칭 subSequence 를 결과로 제공합니다.
4. Boolean matchingYN = matcher.matches();
matcher 의 매칭결과가 Exact Matching 인지 YN 으로 표시합니다.
[ 정규표현식 포스트 ]
1. Character Classes
글자, 숫자, 공백 등을 표시하는 기법, [ ] 캐릭터 하나, ( ) 캐릭터 여러개
http://haloaround.tistory.com/admin/entry/post/?id=183
2. Quandifiers
캐릭터가 몇번 반복되는지, 그리고 어떻게 이런것들을 검색하는지
http://haloaround.tistory.com/admin/entry/post/?id=184
3. Capturing Groups & Boundary Match
매칭단위는 무엇이고 매칭결과를 어디에서 찾아야하는지 등의 검색 조건을 지정하는 기법
http://haloaround.tistory.com/admin/entry/post/?id=185
4. Java Pattern and Matcher Class
Input Sequence 리소스에서 Pattern 에 부합하는 것을 검색하는 기능
http://haloaround.tistory.com/admin/entry/post/?id=186