如何使用 Java 中的正則表示式從字串中提取每個(英語)單詞?


正則表示式“[a-zA-Z]+”匹配一個或多個英語字母。因此,要從給定的輸入字串中提取每個單詞,需要-

  • 使用 Pattern 類的 compile() 方法編譯上述表示式。

  • 使用 Pattern 類的 matcher() 方法,將所需的輸入字串作為引數傳遞,得到 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("Enter sample text: ");
      String data = sc.nextLine();
      String regex = "[a-zA-Z]+";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("Words in the given String: ");
      while(matcher.find()) {
         System.out.println(matcher.group()+" ");
      }
   }
}

輸出

Enter sample text:
Hello this is a sample text
Words in the given String:
Hello
this
is
a
sample
text

更新日期:2019-11-21

1K+ 瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.