1.常用的类和方法
Pattern类:
Pattern.compile(),matcher(String input)
Matcher类:
matches():整个匹配
find():部分匹配
lookAt():从头匹配
group():返回子串
2.简单正则
| :或
[] :范围
[^] :范围非
{} :数量
{a,} :至少a
{a,b} :a到b
() :分组
\ :转义
^ :固定头部
$ :固定尾部
3.等价正则
\d :数字字符
\D :非数字字符
\w :单词字符
\W :非单词字符
. :除换行符(\n)以外的字符
\s :不可见字符
\S :非不可见字符
例题:找出输入串中范围为1000-3999的数字
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
//至少4位数字
String regex = "[0-9]{4,}";
Pattern pattern = Pattern.compile(regex);
Scanner in = new Scanner(System.in);
while(in.hasNextLine()){
String s = in.nextLine();
Matcher matcher = pattern.matcher(s);
//查找字符串中的符合规则的子串(4位数字以上的数字字符串)
while(matcher.find()){
//得到数字子串
String nums = matcher.group();
//数字子串转换成整型
int integer = Integer.valueOf(nums);
//判断区间
if(integer>=1000 && integer<=3999){
System.out.println(integer);
}
}
}
}