在 Java 中查詢所有以“a”開頭的單詞


在 Java 中,可以使用正則表示式透過字串找到所有以“a”開頭的單詞。正則表示式是使用特定模式語法來匹配任何其他字串的字元序列。正則表示式在 java.util.regex 包中可用,該包具有許多類,但最重要的類是模式類和匹配類。

下面給出了一個查詢所有以“a”開頭的單詞的程式,該程式使用的是正則表示式

示例

 即時演示

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) throws Exception {
      String str = "This is an apple";
      String regex = "\ba\w*\b";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(str);
      String word = null;
      System.out.println("The input string is: " + str);
      System.out.println("The Regex is: " + regex + "\r
");       System.out.println("The words that start with a in above string are:");       while (m.find()) {          word = m.group();          System.out.println(word);       }       if (word == null) {          System.out.println("There are no words that start with a");       }    } }

輸出

The input string is: This is an apple
The Regex is: \ba\w*\b
The words that start with a in above string are:
an
apple

更新於: 2019 年 7 月 30 日

540 次瀏覽

啟動您的 職業生涯

完成課程後可獲得認證

開始
廣告