如何在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[] ) {
//正则表达式匹配长度为2到6的非单词字符串
String regex = ".";
Scanner sc = new Scanner(System.in);
System.out.println("Enter your input string: ");
String input = sc.nextLine();
//创建一个Pattern对象
Pattern p = Pattern.compile(regex);
//创建一个Matcher对象
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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短