正则表达式:
是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串
1、字符:
(1)x 字符x
(2)\\ 反斜线
(3)\n 换行符
(4)\r 回车符
2、字符类:
(1)[abc] a、b或c
(2)[^abc] 除a、b或c之外的任何字符
(3)[a-zA-Z] 所有字母
(4)0[0-9] 0-9的数字
3、预定字符类:
(1). 任何字符
(2)\d 数字[0-9]
(3)\D 非数字[^0-9]
(4)\w 单词字符[a-zA-Z_0-9]
(4)\W 非单词字符[^\w]
4、边界匹配器:
(1)^ 行的开头
(2)$ 行的结尾
(3)\b 单词边界(就是不是单词字符的地方)
5、Greedy数量词:
(1)X? 一次或一次也没有
(2)X* 零次或多次
(3)X+ 一次或多次
(4)X{n} 恰好n次
(5)X{n,} 至少n次
(6)X{n,m} 至少n次,但是不超过m次
6、应用:
(1)判断功能:
public boolean matches(String regex)
//举例:
regex = "\\w"; //只能是字母或数字
bollean flag = s.matches(regex);
(2)分割功能:
public String[] split(String regex)
//举例:
String age = "18-24";
String regex = "-";
String[] array = age.split(regex);
(3)替换功能:
public String replaceAll(String regex,String replacement)
//举例:
String s = "123hello00world";
String regex = "\\d";
String s = "*";
String result = s.replaceAll(regex,s);
(4)获取功能:Pattern和Matcher类
Pattern:模式 Matcher:匹配器
//举例:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SplitDemo {
public static void main(String[] args) {
String s = "jin tian tian qi hao qing lang";
String regex = "\\b\\w{3}\\b";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group());
}
}
}
7、常用的正则表达式:
"^\d+$" //非负整数(正整数 + 0)
"^[0-9]*[1-9][0-9]*$" //正整数
"^((-\d+)|(0+))$" //非正整数(负整数 + 0)
"^-[0-9]*[1-9][0-9]*$" //负整数
"^-?\d+$" //整数
"^\d+(\.\d+)?$" //非负浮点数(正浮点数 + 0)
"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$" //正浮点数
"^((-\d+(\.\d+)?)|(0+(\.0+)?))$" //非正浮点数(负浮点数 + 0)
"^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$" //负浮点数
"^(-?\d+)(\.\d+)?$" //浮点数
"^[A-Za-z]+$" //由26个英文字母组成的字符串
"^[A-Z]+$" //由26个英文字母的大写组成的字符串
"^[a-z]+$" //由26个英文字母的小写组成的字符串
"^[A-Za-z0-9]+$" //由数字和26个英文字母组成的字符串
"^\w+$" //由数字、26个英文字母或者下划线组成的字符串
"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$" //email地址