正则表达式是什么?
正则表达式(regular expression)指定了字符串的模式,用于定位匹配某种字符串
使用
如下匹配1个或多个0-9数字,若没有+则只能匹配一个
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
System.out.println(text);
}
如下将1个或多个0-9数字替换为#
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(text);
String s = matcher.replaceAll("#");
System.out.println(s);
常用表达式
^和$表示开头和结尾
表达式 | 含义 |
---|---|
^[0-9]*$ | 0个或多个,0-9数字 |
^[0-9]+$ | 1个或多个,0-9数字 |
^\d{n}$ | n个,0-9数字 |
^\d{n,}$ | 大于等于n个,0-9数字 |
^[1-9][0-9]$ | 10-99 |
^[\u4e00-\u9fa5]{0,}$ | 大于等于0个,汉字 |
^[A-Za-z0-9]+$ | 1个或多个,字母数字 |
详细表达式表格
- . 匹配所有所有字符(除行终止符),如果要匹配 .,则需要转义\.
- XY表示任何X的匹配后面跟随Y的匹配,X|Y表示任何X或Y的匹配