通过使用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\n");
System.out.println("以上述字符串中的a开头的单词是:");
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
以上述字符串中的a开头的单词是:
an
apple