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

Java RegEx를 사용하여 특정 문자열을 매칭하는 방법/행의 끝

원자 문자 " $"은 특정 문자열의 끝을 일치시킵니다. 예를 들어,

  • 표현식 " \\ d $ "와 숫자로 끝나는 문자열"/줄 일치.

  • 표현식 " [az] $ "소문자로 끝나는 문자열을 일치시킵니다"/줄.

예제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 = ".*[^a-zA-Z0-9//s]$";
      //정규 표현식 컴파일
      Pattern pattern = Pattern.compile(regex);
      //검색 매치어 오브젝트
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         System.out.println("일치가 발생했습니다");
      } else {
         System.out.println("일치가 발생하지 않았습니다");
      }
   }
}

출력1

Enter a String
이것은 예제 텍스트입니다#
일치가 발생했습니다

출력2

Enter a String
hello how are you
Match not occurred

예제2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "\\.$";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Pattern 객체 생성
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //Matcher 객체 생성
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println("String "+i+" ends with '.'");
         }
      }
   }
}

출력 결과

Enter 5 input strings:
hello how are you.
where do you live
what is your name.
welcome to w3codebox
The Biggest Online Tutorials Library.
String 0 ends with '.'
String 2 ends with '.'
String 4 ends with '.'
추천해드립니다