在 Java 中查找以"a"开头的所有单词

java 8object oriented programmingprogramming

使用 Java 中的正则表达式可以在字符串中找到以 a 开头的所有单词。正则表达式是字符序列,可用于使用特定模式语法匹配其他字符串。正则表达式在 java.util.regex 包中可用,该包有许多类,但最重要的是 Pattern 类和 Matcher 类。

使用正则表达式查找以"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

相关文章