如何使用 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.