Allen's 데이터 맛집

[1] 특정 패턴의 단어 추출 활용 본문

etc Project/간단한 자연어 데이터 처리

[1] 특정 패턴의 단어 추출 활용

Allen93 2024. 7. 31. 15:18

특정 패턴 추출

 

 

정규식을 사용하면 특정 패턴의 단어를 추출할 수 있습니다. 이번에는 숫자가 포함된 단어를 추출하는 방법을 알아보겠습니다.

import java.util.regex.*;
import java.util.ArrayList;

public class PatternWordExtraction {
    public static void main(String[] args) {
        String text = "Order123, product456, and item789 are in the list.";
        Pattern pattern = Pattern.compile("\\b\\w*\\d+\\w*\\b");
        Matcher matcher = pattern.matcher(text);
        
        ArrayList<String> words = new ArrayList<>();
        while (matcher.find()) {
            words.add(matcher.group());
        }
        
        System.out.println("Words with numbers: " + words);
    }
}

이 코드는 숫자가 포함된 단어를 추출하여 ArrayList에 저장합니다. 정규식 \\b\\w*\\d+\\w*\\b는 단어 경계 내에서 숫자를 포함하는 단어를 찾습니다.

 

 

다중 패턴 추출

여러 패턴을 동시에 추출해야 할 때도 있습니다. 예를 들어, 특정 접두사로 시작하는 단어와 숫자가 포함된 단어를 동시에 추출하려면 다음과 같이 할 수 있습니다

import java.util.regex.*;
import java.util.ArrayList;

public class MultiPatternExtraction {
    public static void main(String[] args) {
        String text = "Error123, log456, and data789 need review.";
        Pattern pattern = Pattern.compile("\\b(error\\w*|\\w*\\d+\\w*)\\b", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(text);
        
        ArrayList<String> words = new ArrayList<>();
        while (matcher.find()) {
            words.add(matcher.group());
        }
        
        System.out.println("Matched patterns: " + words);
    }
}

이 코드는 'error'로 시작하거나 숫자가 포함된 단어를 모두 추출합니다.

 

 

고급 활용: 정규식 최적화

정규식을 최적화하여 성능을 향상시키는 방법도 있습니다. 복잡한 정규식을 사용할 때는 패턴을 미리 컴파일하여 성능을 높일 수 있습니다.

import java.util.regex.*;
import java.util.ArrayList;

public class OptimizedWordExtraction {
    public static void main(String[] args) {
        String text = "Optimize123, this code456, for better789 performance.";
        Pattern pattern = Pattern.compile("\\b\\w*\\d+\\w*\\b");
        Matcher matcher = pattern.matcher(text);
        
        ArrayList<String> words = new ArrayList<>();
        while (matcher.find()) {
            words.add(matcher.group());
        }
        
        System.out.println("Optimized words with numbers: " + words);
    }
}

 

https://github.com/siilver94/java-regex-word-extraction

 

GitHub - siilver94/java-regex-word-extraction

Contribute to siilver94/java-regex-word-extraction development by creating an account on GitHub.

github.com

 

728x90