English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java의 예제를 포함한 Matcher start() 메서드

java.util.regex.Matcher 클래스는 여러 가지 일치 작업을 수행하는 엔진을 나타냅니다. 이 클래스는 생성자가 없으며, 사용할 수 있습니다.matches()java.util.regex.Pattern 클래스의 메서드를 생성/이 클래스의 객체를 가져옵니다.

Matcher 클래스의start()메서드는 일치하는 문자의 시작 인덱스를 반환합니다.

부분 표현식 "[...]"를 입력 문자열에 있는 대括호 안에 지정된 문자와 매칭합니다. 아래의 예제에서는 문자 t를 매칭하는 이 표현식을 사용합니다. 여기서

  • 이를 사용하여compile()메서드는 정규 표현식을 컴파일합니다.

  • Matcher 객체를 얻습니다.

  • matcher()이 메서드를 각 매칭 항목에서 호출합니다.

예제

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartExample {
   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()) {
         int start = matcher.start();
         System.out.println(start);
      }
   }
}

출력 결과

Enter input text:
Hello how are you welcome to w3codebox
26
31
42

문자 t가 입력 문자열에서 세 번 등장했기 때문에 세 개의 인덱스 값(각 문자의 인덱스를 나타냄)을 관찰할 수 있습니다.

추천해드립니다