如何使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP