如何使用 Java 中的正则表达式打印字符串中的所有字符?
元字符“.”匹配所有字符,使用正则表达式打印所有字符,如下所示:-
使用 compile() 方法编译正则表达式。
使用 matcher() 方法创建一个 Matcher 对象。
使用 find() 方法查找匹配项,并为每个匹配项使用 group() 方法打印匹配的内容(字符)。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
//Regular expression to match a string of non-word with length 2 to 6
String regex = ".";
Scanner sc = new Scanner(System.in);
System.out.println("Enter your input string: ");
String input = sc.nextLine();
//Creating a Pattern object
Pattern p = Pattern.compile(regex);
//Creating a Matcher object
Matcher m = p.matcher(input);
while(m.find()) {
System.out.println(m.group());
}
}
}输出
Enter your input string: This is a sample text T h i s i s a s a m p l e t e x t
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP