정규식을 사용한 패턴 매칭
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 47번째.
Pattern과 Matcher 클래스는 Java에서 regex 작업을 위한 강력한 도구를 제공합니다. 먼저, 이를 사용하는 방법을 알아보겠습니다:
Pattern.compile()을 사용하여 pattern을 생성하세요:
Pattern pattern = Pattern.compile("cat");
// Creates a pattern to find "cat"텍스트에 대한 matcher를 생성하세요:
String text = "The cat and dog";
Matcher matcher = pattern.matcher(text);
// Creates a matcher for the text이제 matcher.find()를 사용하여 일치 항목을 찾을 수 있습니다:
while (matcher.find()) {
System.out.println("Found at: " + matcher.start());
}위의 코드를 실행한 후 출력은: Found at: 4
메서드 이해하기:
<b>matcher.find()</b>- 텍스트에서 패턴의 다음 발생을 검색합니다- 일치가 발견되면
true를 반환합니다 - 더 이상 일치가 없으면
false를 반환합니다 - 이것이
while루프에서 사용하는 이유입니다 - 모든 발생을 찾기 위해
- 일치가 발견되면
<b>matcher.start()</b>-find()가 발견한 마지막 일치의 시작 인덱스(위치)를 반환합니다- 우리 예시에서 "cat"은 "The cat and dog"에서 인덱스 4에서 시작합니다
- 성공적인
find()이후에 호출해야 합니다
여러 매치가 있는 예제:
Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher("cat and cat");
while (matcher.find()) {
System.out.println("Found at: " + matcher.start());
}
// Output:
// Found at: 0
// Found at: 8챌린지
쉬움findWords라는 이름을 가진 메서드를 생성하세요. 이 메서드는 두 개의 인수를 받습니다:
- 검색할 String (
text) - 찾을 String (
word)
이 메서드는 다음을 수행해야 합니다:
- Pattern과 Matcher를 사용하여 단어의 모든 발생 위치를 찾으세요
- 단어가 발견된 위치를 포함하는 문자열을 반환하세요
- 위치는 공백으로 구분되어야 합니다
반환 메시지는 다음과 같아야 합니다:
- 입력 중 하나라도 null인 경우: return "Invalid input"
- 단어를 찾지 못한 경우: return "Not found"
- 발견된 경우: 위치 반환 (예: "4 10 15")
치트 시트
Pattern과 Matcher 클래스는 Java에서 정규 표현식 작업을 위한 강력한 도구를 제공합니다.
Pattern.compile()을 사용하여 pattern을 생성하세요:
Pattern pattern = Pattern.compile("cat");
// Creates a pattern to find "cat"텍스트에 대한 matcher를 생성하세요:
String text = "The cat and dog";
Matcher matcher = pattern.matcher(text);
// Creates a matcher for the textmatcher.find()를 사용하여 일치 항목을 찾으세요:
while (matcher.find()) {
System.out.println("Found at: " + matcher.start());
}주요 메서드:
<b>matcher.find()</b>- 패턴의 다음 발생을 검색합니다- 찾은 경우
true, 더 이상 일치가 없는 경우false를 반환합니다 - 모든 발생을 찾기 위해 루프에서 사용하세요
- 찾은 경우
<b>matcher.start()</b>- 마지막으로 찾은 일치의 시작 인덱스를 반환합니다- 성공적인
find()후에 호출하세요
- 성공적인
직접 해보기
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static String findWords(String text, String word) {
// 여기에 코드를 작성하세요
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
String word = scanner.nextLine();
if (text.equals("null")) text = null;
if (word.equals("null")) word = null;
System.out.println(findWords(text, word));
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.