正则表达式是一种字符串的匹配规则,在实际处理正则表达可用来检查输入是否符合规则,或者从字符串中查找数据。一般的语法主要如下:
k k
abc abc
[abc](字符集) a,b,c;匹配一位
[abc][xyz] 匹配ax,ay,az,bx,...,cz
[a-z] 匹配a,b,...,z
[a-zA-Z_0-9] 匹配a,b,...,z,A,B,...,Z,_,0,1,...,9
[^a-zA-Z] 匹配非英文字符
[\u4e00-\u9fa5] 匹配中文
\d [0-9]
\D 排除数字
\w [a-zA-Z_0-9]
\W 排除数字,字母和下划线
\s 匹配空白字符
\S 匹配非空白字符。
. 匹配任意字符
[abc]? 0或1个
[abc]* 0或多个
[abc]+ 至少1个
[abc]{3} 3个
[abc]{3,5} 3-5个(3,4,5个)
[abc]{3,} 至少三个
| 或
(1)匹配身份证的正则表达式
* 123456789012345
* 123456789012345678
* 12345678901234567x
* 12345678901234567X
String regex = "\\d{15}|\\d{17}[\\dxX]";
(2)匹配固定电话的正则表达式
* 1234567
* 12345678
* 010-1234567
* 0102-1234567
* (010)12345678
* (0102)12345678
String regex = "(\\d{3,4}-|\\(\\d{3,4}\\))?\\d{7,8}";
(3)将一些内容中出现的违禁词用***号代替:
String s = new Scanner(System.in).nextLine(); String regex = "草泥马|骂了隔壁|尼玛|你妹|ISIS"; s = s.replaceAll(regex, "***");//将输入的字符串中的不雅词汇用***代替
(4)按照规则拆分字符串,将输入的字符串按照标点符号拆分放到一个字符串数组中。
String s = new Scanner(System.in).nextLine(); //aa,bb;cc dd,,,ee,;,,; ;, ;,; ff String regex = "[,; ]+"; String[] a = s.split(regex);
(5)提取符合要求的字符串
Pattern p = Pattern.compile(正则表达式);
Matcher m = p.matcher(要匹配的字符串);//创建对象
public class Test { public static void main(String[] args) { System.out.println("请输入:"); String s = new Scanner(System.in).nextLine();//dfsd123456fg569 String regex="\\d{3,}";//从字符串s中提取3个以上数字的子串。 Matcher m = Pattern.compile(regex).matcher(s); String sub; while(m.find()){ sub = m.group(); int start = m.start(); int end = m.end(); System.out.println(start+","+end+": "+sub);//4,10: 123456;12,15: 569 } } }
原文:http://www.cnblogs.com/fazheng/p/5080761.html