字符类:减法 - Java 正则表达式
javaobject oriented programmingprogramming更新于 2025/2/12 2:20:17
您可以从一个范围中减去另一个范围并将其用作新范围。您可以使用两种字符类变体(即否定和交集)来实现这一点。
例如,范围 [a-l] 和 [^e-h] 的交集为您提供字符 a 到 l,作为范围减去字符 [e-h] 的结果
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入输入文本:");
String input = sc.nextLine();
String regex = "[a-l&&[^e-h]]";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//匹配字符串中的编译模式
Matcher matcher = pattern.matcher(input);
int count =0;
while (matcher.find()) {
count++;
System.out.print(matcher.group()+" ");
}
System.out.println("Number of matched characters: "+count);
}
}
输出
Enter input text: abcdefghijklmnopq a b c d i j k l Number of matched characters: 8
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

