Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

예제가 있는 Java의 Matcher regionEnd() 메서드

<시간/>

java.util.regex.Matcher 클래스는 다양한 일치 작업을 수행하는 엔진을 나타냅니다. 이 클래스에 대한 생성자가 없습니다. java.util.regex.Pattern 클래스의 match() 메소드를 사용하여 이 클래스의 객체를 생성/얻을 수 있습니다.

regionEnd() 이 (Matcher) 클래스의 메소드는 현재 matcher 객체의 끝 인덱스를 나타내는 정수 값을 반환합니다.

예시 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionEndExample {
   public static void main(String[] args) {
      String regex = "(.*)(\\d+)(.*)";
      String input = "This is a sample Text, 1234, with numbers in between.";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      //Setting the region of the matcher
      matcher.region(5, 20);
      if(matcher.matches()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
      System.out.print("End of the region: "+matcher.regionEnd());
   }
}

출력

Match not found
End of the region: 20

예시 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionEndExample {
   public static void main(String[] args) {
      //Regular expression to accepts 6 to 10 characters
      String regex = "[#]";
      System.out.println("Enter a string: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      //Setting region to the input string
      matcher.region(2, 4);
      //Switching to transparent bounds
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
      System.out.println("Ending of the region: "+ matcher.regionEnd());
   }
}

출력

Enter a string:
this is sample text #
Match not found
Ending of the region: 4