Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java 정규식으로 인쇄 불가능한 문자(제어 문자) 매칭하는 방법

텍스트 처리에서 자주 마주치는 인쇄 불가능한(non-printable) 문자는 일반적으로 7가지이며, 각 문자는 고유한 16진수 표현을 가지고 있습니다. Java의 정규식(java.util.regex)을 활용하면 이러한 제어 문자를 손쉽게 찾아내고 개수를 세거나 치환할 수 있습니다.

주요 인쇄 불가능한 문자 목록

이름이스케이프 표기16진수 표현
벨(bell)\a0x07
이스케이프(escape)\e0x1B
폼 피드(form feed)\f0x0C
라인 피드(line feed)\n0x0A
캐리지 리턴(carriage return)\r0x0D
수평 탭(horizontal tab)\t0x09
수직 탭(vertical tab)\v0x0B

예제 1: 이스케이프 시퀀스로 탭 문자 세기

다음 Java 프로그램은 입력받은 텍스트에서 탭(tab) 공백의 개수를 세는 예제입니다. 정규식 \\t를 사용해 수평 탭 문자를 매칭합니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text: ");
        String input = sc.nextLine();

        String regex = "\\t";
        // 패턴 객체 생성
        Pattern pattern = Pattern.compile(regex);
        // 컴파일된 패턴을 문자열과 매칭
        Matcher matcher = pattern.matcher(input);

        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println("입력 텍스트 내 탭 공백 개수: " + count);
    }
}

실행 결과

Enter input text:
sample text with tab spaces
입력 텍스트 내 탭 공백 개수: 3

예제 2: 16진수 표현으로 매칭하기

인쇄 불가능한 문자는 각각의 16진수 표현을 사용해서도 매칭할 수 있습니다. 탭 문자의 16진수 값은 0x09이므로, 정규식에서 \\x09와 같이 작성하면 \\t와 동일하게 동작합니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text: ");
        String input = sc.nextLine();

        String regex = "\\x09"; // 탭 문자의 16진수 표현
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println("입력 텍스트 내 탭 공백 개수: " + count);
    }
}

실행 결과

Enter input text:
sample data with tab spaces
입력 텍스트 내 탭 공백 개수: 4

참고: 모든 제어 문자를 한 번에 매칭하기

특정 문자 하나가 아니라 모든 제어 문자를 한꺼번에 찾고 싶다면 POSIX 문자 클래스인 \\p{Cntrl}을 사용할 수 있습니다. 이 패턴은 위 표에 나온 7가지 문자를 포함해 ASCII 범위의 모든 제어 문자(0x00~0x1F, 0x7F)와 매칭됩니다.

String regex = "\\p{Cntrl}"; // 모든 제어 문자 매칭

또한 매칭된 문자를 제거하고 싶다면 input.replaceAll(regex, "")처럼 활용하면 텍스트를 정제(cleansing)할 때 유용합니다.