如何使用 Java RegEx 匹配一组固定字符
javaobject oriented programmingprogramming更新于 2024/5/5 4:28:17
字符类允许您从一组固定字符中接受单个字符。例如,
表达式 “[tmp]” 匹配字符 t 或 m 或 p。
表达式 “[^tp]” 匹配除 t 或 p 之外的字符。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("输入字符串");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//匹配字符 t 或、m 或、p 的正则表达式
String regex = "[tmp]";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Occurrences: "+count);
}
}
输出
输入字符串 hello how are you welcome to tutorialspoint 出现次数:6
示例 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "[^abcdef]";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Occurrences :"+count);
}
}
输出
输入字符串 Hello how are you welcome to tutorialspoint Occurrences :36
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

