如何使用 Java 正则表达式匹配一系列字符
若要匹配一系列字符,即要匹配序列中两个指定字符之间的所有字符,可以用字符类
[a-z]
表达式“[a-zA-Z]”接受任何英文字母。
表达式“[0-9&&[^35]]”接受 3 和 5 以外的数字。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "^[a-zA-Z0-9]*$";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.matches()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}输出 1
Enter a String Hello Match occurred
输出 2
Enter a String sample# Match not occurred
示例 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "[0-9&&[^35]]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Occurrences :"+count);
}
}输出
Enter a String 111223333555689 Occurrences :8
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP