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

Java에서 정규 표현식을 사용하여 각 영어 단어를 추출하는 방법

정규 표현식 " [a-zA-Z] + ”匹配一个或英文字母。因此,要提取给定输入字符串中的每个单词-

  • 구성compile()Pattern 클래스의 메서드의 위 표현식.

  • 필요한 입력 문자열을 떠나서}}matcher()Pattern 클래스 메서드의 매개변수로 Matcher 객체를 얻습니다.

  • 마지막으로, 매칭된 각 항목에 대해group()매칭된 문자를 얻는 방법.

예제

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EachWordExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("sample 텍스트를 입력하세요: ");
      String data = sc.nextLine();
      String regex = "[a-zA-Z]+";
      //모델 객체를 생성합니다
      Pattern pattern = Pattern.compile(regex);
      //Matcher 객체를 생성합니다
      Matcher matcher = pattern.matcher(data);
      System.out.println("주어진 문자열에 있는 단어: ");
      while(matcher.find()) {
         System.out.println(matcher.group())+"");
      }
   }
}

출력 결과

sample 텍스트를 입력하세요:
Hello this is a sample text
주어진 문자열에 있는 단어:
Hello
this
is
a
sample
text
추천 드립니다