一.正则表达式
*用于对字符串进行匹配,验证或者截取
*正则表达式定义了字符串的模式。
*正则表达式可以用来搜索、编辑或处理文本。
*正则表达式并不仅限于某一种语言,但是在每种语言中有细微的差别。
二.Java中正则表达式常用的三个类
Pattern 类:
pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数。
matches(String regex, CharSequence input) 编译给定正则表达式并尝试将给定输入与其匹配。 |
Matcher 类:
Matcher 对象是对输入字符串进行解释和匹配操作的引擎。与Pattern 类一样,Matcher 也没有公共构造方法。你需要调用 Pattern 对象的 matcher 方法来获得一个 Matcher 对象。
find() 尝试查找与该模式匹配的输入序列的下一个子序列。 |
lookingAt() 尝试将从区域开头开始的输入序列与该模式匹配。 |
lookingAt() 尝试将从区域开头开始的输入序列与该模式匹配。 |
groupCount() 返回此匹配器模式中的捕获组数。 |
PatternSyntaxException:
PatternSyntaxException 是一个非强制异常类,它表示一个正则表达式模式中的语法错误。
示例代码:
package com.day23;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
*图片的参考正则:
*<img[\\s\\S]{0,200}alt=\"([^\"]{0,50})\"[\\s\\S]{0,200}src=\"([^\"]{1,200})\"
*/
public class RegexBase {
public static void main(String[] args) {
demo1();
demo2();
}
public static void demo1(){
String regex = "[a-zA-Z][\\w-]{5,7}";
String str = "A45646*4";
System.out.println(Pattern.matches(regex, str));
}
public static void demo2(){
String regex = "^(0\\d{2,3}-)?\\d{7,8}$";
String str = "028-58965599dhaiudya8d7ada89585555jdaoihda0698-4567894";
//获得正则表达式的管理对象
Pattern pa = Pattern.compile(regex);
//传入字符串,获取正则与字符串的匹配引擎
Matcher ma = pa.matcher(str);
//查找符合要求的字符串
while(ma.find()){
System.out.println(ma.group());//0返回匹配到的整个字符串 1之后,分别返回第一个及之后的括号内匹配的内容
System.out.println(ma.groupCount());//返回表达式中括号的个数
}
System.out.println(ma.lookingAt());
//System.out.println(ma.group());
}
}
详细教程:正则表达式教程