参考
- ‘x’就表示匹配x本身
- \ 匹配 \
- \n 换行(’\u000A’)
- \r 回车(’\u000D‘)
- [abc]匹配一个字符,a,b,c都可以
- [^abc] 除了a和b和c任意一个
- [a-zA-Z]匹配一个,在范围之间任意一个
- [0-9]匹配0-9任意一个
- . 匹配任意一个;.表示匹配.本身
- \d 匹配一个数字 = [0-9]
- \w 匹配一个字符 [a-zA-Z_0-9] 数字字母下划线
- ^ 表示开头,$表示结尾,\b表示单词边界(不是\w的地方就是)
- 举例 hello world%?haha;xixi (其中空格,%,?,;都是是单词边界)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo07 {
public static void main(String[] args) {
// 需要匹配的字符串
String res = "abc 123 456 asdd hello wolrd!";
// 规则
String regex = "\\d{3}";
// pattern
Pattern p = Pattern.compile(regex);
// 匹配器
Matcher m = p.matcher(res);
while (m.find()){
System.out.println(m.group()); // group()返回匹配的子对象
System.out.println(m.start()); // 第一个匹配成功子串的开始索引
System.out.println(m.end()); // 第一个匹配成功子串结尾索引+1
}
}
}