반응형

정규표현식 예제

public class RegexExam {
    public static void main(String[] args) {
        System.out.println(findByRegex("\\d{3}-\\d{4}-\\d{4}", "전화번호는 010-0000-0000입니다."));
    }

    private static List<String> findByRegex(String regex, String text) {
        List<String> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            // System.out.println("찾은 문자열의 시작 인덱스 : " + matcher.start());
            // System.out.println("찾은 문자열의 종료 인덱스 : " + matcher.end());
            // System.out.println("찾은 문자열 : " + matcher.group());
            result.add(matcher.group());
        }

        return result;
    }
}

전화번호 찾기

// 010, 011, 016, 017, 018, 019로 시작되어야함
// 가운데는 3자리 혹은 4자리여야함
System.out.println(findByRegex("01[016789]-\\d{3,4}-\\d{4}", "010-0000-0000")); // [010-0000-0000]
System.out.println(findByRegex("01[016789]-\\d{3,4}-\\d{4}", "012-0000-0000")); // []

영어 문장만 찾기

System.out.println(findByRegex("[a-zA-Z\\s]+", "$$$iloveyou###Hello World@@@@")); // [iloveyou, Hello World]

이메일 포맷 체크

System.out.println(findByRegex("^[a-zA-Z\\d_]+@\\w+\\.\\w+$", "iore_8655@naver.com")); // [iore_8655@naver.com]

Greedy, Lazy

// Greedy
System.out.println(findByRegex("\\d.*-", "000-111-222")); // [000-111-]

// Lazy
System.out.println(findByRegex("\\d.*?-", "000-111-222")); // [000-, 111-]
반응형

'Development > Java' 카테고리의 다른 글

[Java] Reflection  (0) 2021.03.03
[Java] Simple Machine Learning  (0) 2021.02.27
[Java] Thread Dump  (0) 2020.12.28
[Java] Heap Dump  (0) 2020.12.28
[Java] 명령어  (0) 2020.12.28

+ Recent posts