Java 中的正则表达式元字符
javaobject oriented programmingprogramming更新于 2024/5/5 3:24:17
子表达式/元字符"\t"与制表符空格匹配。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\t";
Scanner sc = new Scanner(System.in);
System.out.println("输入一个字符串:");
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count ++;
}
System.out.println("制表符空格数:"+count);
}
}
输出
输入一个字符串: This is a sentence with tab spaces 制表符空格数:6
示例 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\t";
Scanner sc = new Scanner(System.in);
System.out.println("输入字符串:");
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
String result = "";
while(m.find()) {
result = m.replaceAll(" ");
}
System.out.println("结果: "+result);
}
}
输出
输入一个字符串: This is a sentence with tab spaces 结果:This is a sentence with tab spaces
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

