Java에서 정규식(Regex)은 java.util.regex 패키지의 Pattern 및 Matcher 클래스를 사용하여 처리됩니다.
- Pattern : 정규식 패턴을 정의하는 클래스
- Matcher : 패턴과 문자열을 매칭하는 클래스
- PatternSyntaxException : 정규식 구문 오류 예외
1. 정규식 기본 문법
패턴 | 설명 | 예제 |
. | 임의의 문자 (줄바꿈 제외) | "a.c" → "abc", "a3c" 매칭 |
^ | 문자열의 시작 | "^Hello" → "Hello world" 매칭 |
$ | 문자열의 끝 | "world$" → "Hello world" 매칭 |
* | 0개 이상 반복 | "a*" → "", "a", "aaa" |
+ | 1개 이상 반복 | "a+" → "a", "aaa" (빈 문자열 X) |
? | 0개 또는 1개 | "a?" → "", "a" |
{n} | 정확히 n개 반복 | "a{3}" → "aaa" |
{n,} | n개 이상 반복 | "a{2,}" → "aa", "aaa", "aaaa" |
{n,m} | n개 이상 m개 이하 반복 | "a{2,4}" → "aa", "aaa", "aaaa" |
[] | 문자 집합 (ex: [abc] → a 또는 b 또는 c) | "[abc]" → "a", "b", "c" |
[^] | 제외 문자 (ex: [^abc] → a, b, c 제외) | "[^abc]" → "d", "e" (a, b, c 제외) |
() | 그룹화 (ex: (abc)+ → abc 1번 이상 반복) | "(abc)" → "abc" |
\d | 숫자 [0-9] | "\d" → "1", "5", "9" |
\D | 숫자가 아닌 문자 [^0-9] | "\D" → "a", "B", "@" |
\w | 알파벳 + 숫자 + _([a-zA-Z0-9_]) | "\w" → "a", "Z", "9", "_" |
\W | \w가 아닌 문자 | "\W" → "@", "#", " " |
\s | 공백 문자 (스페이스, 탭, 개행) | "\s" → " ", "\n", "\t" |
\S | 공백이 아닌 문자 | "\S" → "a", "1", "@" |
2. 정규식 활용 예제
문자열이 특정 패턴과 일치하는지 확인
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String pattern = "\\d{3}-\\d{4}-\\d{4}"; // 010-1234-5678 형식
String input = "010-1234-5678";
boolean isMatch = Pattern.matches(pattern, input);
System.out.println("일치 여부: " + isMatch); // true
}
}
패턴에 맞는 문자열 찾기 (find)
import java.util.regex.*;
public class RegexFindExample {
public static void main(String[] args) {
String text = "My phone number is 010-1234-5678.";
String pattern = "\\d{3}-\\d{4}-\\d{4}";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
// find() : 패턴과 일치하는 부분을 찾음
if (m.find()) {
// group() : 매칭된 문자열 반환
System.out.println("찾은 값: " + m.group()); // 010-1234-5678
}
}
}
여러 개의 패턴 찾기
import java.util.regex.*;
public class RegexMultipleMatch {
public static void main(String[] args) {
String text = "Emails: test@example.com, hello@domain.net";
String pattern = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println("이메일 찾음: " + m.group());
// 이메일 찾음: test@example.com
// 이메일 찾음: hello@domain.net
}
}
}
문자열을 정규식으로 분리 (split)
import java.util.regex.*;
public class RegexSplitExample {
public static void main(String[] args) {
String text = "apple,banana;grape orange";
String[] result = text.split("[,; ]"); // 쉼표(,), 세미콜론(;), 공백( )으로 분리
for (String word : result) {
System.out.println(word);
}
}
}
출력 결과
apple
banana
grape
orange
문자열 치환 (replaceAll)
import java.util.regex.*;
public class RegexReplaceExample {
public static void main(String[] args) {
String text = "Hello 123, this is a test 456!";
String result = text.replaceAll("\\d+", "[NUMBER]"); // 숫자 제거
System.out.println(result); // Hello [NUMBER], this is a test [NUMBER]!
}
}
3. 자주 쓰는 정규식 패턴
용도 | 정규식 |
이메일 검사 | ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ |
전화번호 (010-1234-5678) | ^010-\d{4}-\d{4}$ |
URL 검사 | ^(https? |
한글만 포함 | ^[가-힣]+$ |
영문자만 포함 | ^[a-zA-Z]+$ |
숫자만 포함 | ^\d+$ |
비밀번호 (영문+숫자 조합, 8~16자) | ^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$ |
4. 정규식 플래그
Pattern.compile("pattern", Pattern.CASE_INSENSITIVE);
플래그 | 설명 |
Pattern.CASE_INSENSITIVE | 대소문자 구분 안 함 |
Pattern.MULTILINE | 여러 줄 모드 ( ^ 와 $ 가 줄마다 적용됨) |
Pattern.DOTALL | . 이 개행 문자( \n ) 포함 모든 문자에 매칭됨 |
Pattern.UNICODE_CASE | 유니코드 문자에 대해 대소문자 무시 |
Pattern.COMMENTS | 공백과 # 이후 주석 무시 |
5. Stream과 정규식 활용
import java.util.regex.Pattern;
public class StreamRegex {
public static void main(String[] args) {
String text = "Java 8, Java 11, Java 17";
Pattern.compile("\\d+")
.matcher(text)
.results()
.map(m -> "버전: " + m.group())
.forEach(System.out::println);
}
}
출력 결과
버전: 8
버전: 11
버전: 17
Java에서 정규식을 활용하면 문자열 검사, 파싱, 치환 등의 작업을 효과적으로 수행할 수 있습니다.
'BackEnd > JAVA' 카테고리의 다른 글
[JAVA] Stream API Collect 메소드 (0) | 2025.02.20 |
---|---|
[JAVA] Stream API 생성과 사용법 정리 (2) | 2025.02.15 |
[JAVA] Checked Exception과 Unchecked Exception 차이점 (0) | 2025.02.13 |