🎯 목표 : 정규 표현식의 활용 이해
Pattern 클래스 주요 메서드
compile(String regex) : 주어진 정규표현식으로부터 패턴을 만든다
matcher(CharSequence input) : 대상 문자열이 패턴과 일치할 경우 true를 반환.
asPredicate() : 문자열을 일치시키는 데 사용할 수있는 술어를 작성.
pattern() : 컴파일된 정규표현식을 String 형태로 반환.
split(CharSequence input) : 문자열을 주어진 인자값 CharSequence 패턴에 따라 분리.
Parttern 플래그 값 사용(상수)
Pattern.CANON_EQ : None표준화된 매칭 모드를 활성화.
Pattern.CASE_INSENSITIVE : 대소문자를 구분하지 않는다.
Pattern.COMMENTS : 공백과 #으로 시작하는 주석이 라인 끝까지 무시.
Pattern.MULTILINE : 수식 ‘^’ 는 라인의 시작과, ‘$’ 는 라인의 끝과 match .
Pattern.DOTALL : 수식 ‘.’과 모든 문자와 match 되고 ‘\n’ 도 match 에 포함.
Pattern.UNICODE_CASE : 유니코드를 기준으로 대소문자 구분 없이 match.
Pattert.UNIX_LINES : 수식 ‘.’ 과 ‘^’ 및 ‘$’의 match시에 한 라인의 끝을 의미하는 ‘\n’만 인식.
String pattern = "^[0-9]*$"; // 숫자만 있는지 여부
String str = "9373846382";
boolean result = Pattern.matches(pattern, str);
System.out.println(result);
// true
String email = "kimcoding@codestates.com";
String phoneNum = "010-1234-1234";
String regExpMail = "\\w+@\\w+\\.\\w+(\\.\\w+)?";
String regExpPhoneNum = "^01(?:0|1|[6-9])-(?:\d{3}|\d{4})-\d{4}$";
//Patten.matches 메소드를 사용하여, 결과를 boolean타입으로 확인.
if(Pattern.matches(regExpMail, email)) System.out.println("올바른 이메일 주소입니다.");
else System.out.println("정확한 이메일 주소를 입력해 주세요.");
if(Pattern.matches(regExpPhoneNum, phoneNum)) System.out.println("정상 입력 되었습니다.");
else System.out.println("정확한 번호를 입력해 주세요.");
public boolean solutionFor(String str) {
if(str.length() == 5 || str.length() == 7) {
for(int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i))) return false;
}
return true;
}
return false;
}
public boolean solutionRegular(String str) {
String regExp = "\\d{5}$|\\d{7}$"
return Pattern.matches(regExp, str)
}
정규 표현식 | 설명 |
---|---|
^[0-9]*$ | 숫자 |
^[a-zA-Z]*$ | 영문자 |
^[가-힣]*$ | 한글 |
\w+@\w+.\w+{\.\w+}? | |
^\d{2,3}-\d{3,4}-\d{4}$ | 전화번호 |
^010-\d{3,4}-\d{4}$ | 휴대전화번호 |
\d{6} - [1-4]\d{6} | 주민등록번호 |
^\d{3}-\d{2}$ | 우편번호 |
플래그 | 설명 |
---|---|
i | 대소문자 구분없음: 매칭이 대소문자를 구분하지 않도록 설정. |
g | 전체 검색: 입력 문자열 전체를 대상으로 패턴을 검색. |
m | 멀티 라인: 앵터 메타 문자가 각 줄마다 동작하도록 설정. |
Reference
https://github.com/ziishaned/learn-regex/blob/master/translations/README-ko.md