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]!
}
}
Java Stream API에서 collect() 메서드는 스트림의 요소들을 컬렉션으로 집계하거나, 다양한 방식으로 결과를 처리할 때 사용됩니다. 주로 Collectors 유틸리티 클래스와 함께 사용되며, 리스트 변환, 그룹화, 조인, 맵핑 등의 기능을 제공합니다. 가장 많이 사용되는 컬렉는 Collectors.toList(), Collectors.toSet(), Collectors.toMap() 등이 있습니다.
주요 Collectors 메소드
1. 리스트(List)나 집합(Set)으로 변환 - toList(), toSet(), toMap()
public class CollectExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("Java", "Stream", "API");
String result = words.stream()
.collect(Collectors.joining(", "));
System.out.println(result); // Java, Stream, API
}
}
4. 값 합산, 평균, 통계 - summingInt(), averagingInt(), summarizingInt()
public class CollectExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Ava", "Bob", "Charlie", "Chan", "David", "Eva");
// 첫 글자를 기준으로 이름 그룹화
Map<Character, List<String>> groupedByFirstLetter = names.stream()
.collect(Collectors.groupingBy(name -> name.charAt(0))); // 첫 글자를 기준으로 그룹화
System.out.println(groupedByFirstLetter);
// {A=[Alice, Ava], B=[Bob], C=[Charlie, Chan], D=[David], E=[Eva]}
}
}
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name;
}
}
public class CollectExample {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 30),
new Person("David", 25)
);
// 나이별 그룹화
Map<Integer, List<Person>> groupedByAge = people.stream()
.collect(Collectors.groupingBy(person -> person.age));
// {25=[Bob, David], 30=[Alice, Charlie]}
System.out.println(groupedByAge);
}
}
6. 그룹화 + 개수 세기 - groupingBy() + counting()
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name;
}
}
public class CollectExample {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 30),
new Person("David", 25)
);
Map<Integer, Long> countByAge = people.stream()
.collect(Collectors.groupingBy(person -> person.age, Collectors.counting()));
System.out.println(countByAge); // {30=2, 25=2}
}
}
7. 조건에 따른 분할 - partitioningBy()
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name;
}
}
public class CollectExample {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 30),
new Person("David", 25)
);
Map<Boolean, List<Person>> partitioned = people.stream()
.collect(Collectors.partitioningBy(person -> person.age >= 30));
System.out.println(partitioned);
}
}
정리
collect()는 Java Stream API에서 매우 중요한 메서드로, 다양한 방식으로 데이터를 집계하는 데 사용됩니다. Collectors.toList(), Collectors.toSet(), Collectors.toMap() 외에도 그룹화, 합산, 평균 계산, 요소 결합 등 여러 가지 유용한 방법들이 제공되므로 필요에 따라 적절히 활용할 수 있습니다.
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// 합계 계산
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum); // 출력: Sum: 15
// 평균 계산
double average = numbers.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0);
System.out.println("Average: " + average); // 출력: Average: 3.0
}
}
리듀스(reduce)
요소를 결합하여 단일 결과를 생성합니다.
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// 모든 숫자의 곱 계산
int product = numbers.stream()
.reduce(1, (a, b) -> a * b);
System.out.println("Product: " + product); // 출력: Product: 120
// 모든 숫자의 합 계산
int sum = Stream.of(1, 2, 3, 4, 5).reduce(0, (a, b) -> a + b);
System.out.println(sum); // 15
}
}
조건검사(anyMatch, allMatch, noneMatch)
요소가 특정 조건을 만족하는지 검사합니다.
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// 모든 요소가 0보다 큰지 확인
boolean allPositive = numbers.stream()
.allMatch(n -> n > 0);
System.out.println("All positive: " + allPositive); // 출력: All positive: true
// 3보다 큰 요소가 하나라도 있는지 확인
boolean anyGreaterThanThree = numbers.stream()
.anyMatch(n -> n > 3);
// 출력: Any greater than 3: true
System.out.println("Any greater than 3: " + anyGreaterThanThree);
}
}
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date");
// 병렬 스트림으로 처리
fruits.parallelStream()
.forEach(System.out::println); // 순서가 보장되지 않음
}
}
5. Stream 활용 예제
짝수만 필터링 후 제곱 값 리스트 생성
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> result = numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println(result); // [4, 16, 36]
}
}
문자열 리스트에서 가장 긴 단어 찾기
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "watermelon");
String longestWord = words.stream()
.max(Comparator.comparingInt(String::length))
.orElse("No words");
System.out.println(longestWord); // watermelon
}
}
특정 키워드를 포함하는 개수 구하기
import java.util.stream.Stream;
public class StreamExample {
public static void main(String[] args) {
long count = Stream.of("java", "javascript", "python", "c++")
.filter(s -> s.contains("java"))
.count();
System.out.println(count); // 2
}
}
forEach, count, collect 사용
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamExample {
public static void main(String[] args) {
Stream.of("A", "B", "C").forEach(System.out::println); // 출력: A, B, C
long count = Stream.of(1, 2, 3, 4, 5).count();
System.out.println(count); // 출력: 5
// 스트림에서 List 저장
List<String> list = Stream.of("A", "B", "C").collect(Collectors.toList());
System.out.println(list);
}
}
6. 정리
Java의 Stream API는 컬렉션 데이터를 처리하는 데 매우 강력한 도구입니다. 위의 예제들은 Stream의 주요 기능을 보여주며, 이를 활용하면 데이터를 효과적으로 처리하면서 코드를 더 간결하고 가독성 있게 작성할 수 있습니다. 상황에 맞게 적절한 기능을 선택하여 사용하면 됩니다. 또한 병렬 스트림을 활용하면 성능 최적화도 가능합니다.
자바에서 예외(Exception)는 크게 Checked Exception과 Unchecked Exception으로 나뉩니다.
1. Checked Exception
개념
- 컴파일 시점에 반드시 예외 처리를 해야 하는 예외 - try-catch 문으로 처리하거나 throws 키워드를 사용하여 호출자에게 예외 처리를 위임해야 함 - 예외 처리를 하지 않으면 컴파일 오류 발생
대표적인 Checked Exception
- IOException → 파일 입출력 시 발생 - SQLException → 데이터베이스 관련 예외 - ClassNotFoundException → 클래스 로드 실패 - InterruptedException → 스레드 인터럽트 발생
예제
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fr = new FileReader(file); // FileNotFoundException 발생 가능
} catch (IOException e) { // IOException을 반드시 처리해야 함
System.out.println("파일을 찾을 수 없습니다: " + e.getMessage());
}
}
}
2. Unchecked Exception
개념
- 런타임(Runtime)에서 발생하는 예외 - 컴파일 시점에서는 예외 처리를 강제하지 않음 - 대부분 프로그래머의 실수로 인해 발생
대표적인 Unchecked Exception
- NullPointerException → null 객체에 접근 - ArrayIndexOutOfBoundsException → 배열의 인덱스를 초과 - ArithmeticException → 0으로 나누기 - ClassCastException → 잘못된 형 변환
예제
public class UncheckedExceptionExample {
public static void main(String[] args) {
String text = null;
System.out.println(text.length()); // NullPointerException 발생
}
}