如何使用 Java 中的正则表达式从字符串中提取每个(英语)单词?

javaobject oriented programmingprogramming更新于 2024/5/11 8:44:17

正则表达式"[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("输入示例文本:");
      String data = sc.nextLine();
      String regex = "[a-zA-Z]+";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个匹配器对象
      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

相关文章


有用资源