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

Java 정규식(RegEx)으로 단어 경계가 아닌 위치(\B)를 매칭하는 방법

Java 정규 표현식(Regular Expression)에서 메타 문자 \B를 사용하면 단어 경계가 아닌(non-word boundary) 위치를 매칭할 수 있습니다. 일반적으로 \b가 단어 문자와 비단어 문자 사이의 경계, 즉 단어의 시작과 끝을 의미한다면, \B는 그 반대로 두 단어 문자가 연속해서 이어지는 지점, 즉 단어의 내부를 가리킵니다.

예제 1 – 단어 경계가 아닌 위치 개수 세기

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //사용자로부터 문자열 입력 받기
      System.out.println("문자열을 입력하세요");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\\B";
      //정규 표현식 컴파일
      Pattern pattern = Pattern.compile(regex);
      //Matcher 객체 생성
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("단어 경계가 아닌 위치의 개수: "+count);
   }
}

실행 결과

문자열을 입력하세요
this is a sample text
단어 경계가 아닌 위치의 개수: 12

"this is a sample text"라는 문장에는 각 단어 내부에서 글자와 글자가 맞닿는 지점이 총 12개 있습니다(this 3개, is 1개, sample 5개, text 3개). 이처럼 \B는 공백 없이 단어 문자들이 연속되는 모든 위치에서 매칭됩니다.

예제 2 – 특정 패턴과 함께 \B 활용하기

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      String regex = "\\Bin";
      Scanner sc = new Scanner(System.in);
      System.out.println("문자열을 입력하세요: ");
      String input = sc.nextLine();
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("단어 내부에서 발견된 횟수: "+count);
   }
}

실행 결과

문자열을 입력하세요: 
this is a sample text in win tin pin sin
단어 내부에서 발견된 횟수: 4

두 번째 예제의 정규식 \Bin은 단어 경계가 아닌 위치에 있는 "in"만 찾습니다. 따라서 독립된 단어인 "in"은 제외되고, win, tin, pin, sin처럼 다른 단어 안에 포함된 "in" 4개만 매칭됩니다. 이렇게 \B를 활용하면 단어의 일부분에 해당하는 패턴만 정확하게 골라낼 수 있습니다.