字符类:相交 - Java 正则表达式
Java 正则表达式中使用方括号 “[ ]” 定义字符类,此子表达式匹配指定或可能的一组字符中的单个字符。例如,正则表达式 [abc] 匹配单个字符 a 或 b 或 c。
字符类的相交变体允许你匹配在具有相交关系的范围中常见的字符。
使用 && 定义范围之间的相交关系,即表达式 [a-z&&[r-u]] 匹配 r 到 u 的单个字符。
示例
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("Enter input text: ");
String input = sc.nextLine();
String regex = "[a-z&&[r-u]]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
int count =0;
while (matcher.find()) {
count++;
}
System.out.println("Number of matched characters: "+count);
}
}输出
Enter input text: how are you welcome to tutorialspoint Number of matched characters: 9
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP