在 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 次浏览

启动您的 职业生涯

完成课程后可获得认证

开始
广告
© . All rights reserved.