package com.test.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * String 关于正则表达式的三个方法 String.matches() String.split() String.replace() * * @author, create on 2014-5-31 下午2:05:45 * */ public class Test { public void testMatches() { String str = "13516213428"; boolean b = Pattern.matches("1[3-8]\\d{9}", str); System.out.println("phone:" + b); str = "labreeze@126.com"; b = Pattern.matches("\\w{1,}@\\w{1,}(.com|.net|.cn|.org)", str); System.out.println("email:" + b); // 或者另一种写法 详见java源码 // public static boolean matches(String regex, CharSequence input) { // Pattern p = Pattern.compile(regex); // Matcher m = p.matcher(input); // return m.matches(); // } final Pattern pattern = Pattern .compile("\\w{1,}@\\w{1,}(.com|.net|.cn|.org)"); final Matcher matcher = pattern.matcher("labreeze@126.com"); b = matcher.matches(); System.out.println("another:" + b); } /** * result: this\n is\n my\n world */ public void testMatcher() { final Pattern pattern = Pattern.compile("\\w{1,}"); final Matcher matcher = pattern.matcher("this is my world"); while (matcher.find()) { System.out.println(matcher.group()); } // 从指定位置开始查找正则表达式 final int i = 5; if (matcher.find(i)) { System.out.println(matcher.group()); } } public void testSplit() { final Pattern pattern = Pattern.compile("--"); final String inputString = "hello--this--is--my--world"; String[] strs = pattern.split(inputString); for (final String s : strs) { System.out.println(s); } // 限制分段 strs = pattern.split(inputString, 2); for (final String s : strs) { System.out.println(s); } } /** * 正则表达式之替换 */ public void testReplace() { final Pattern pattern = Pattern.compile("正则表达式"); final Matcher matcher = pattern .matcher("正则表达式 Hello World,正则表达式 Hello World"); // 替换第一个符合正则的数据 System.out.println(matcher.replaceFirst("Java")); System.out.println(matcher.replaceAll("Java")); } public static void main(final String[] args) { final Test test = new Test(); // test.testMatches(); // test.testMatcher(); // test.testSplit(); test.testReplace(); } }
相关推荐
本文写作时,一个包含了用正则表达式进行文本处理的Java规范需求(Specification Request)已经得到认可,你可以期待在JDK的下一版本中看到它。 然而,如果现在就需要使用正则表达式,又该怎么办呢?你可以从Apache...
java,正则表达式,详解,java正则表达式,PDF
Java正则表达式 Java 正则表达式 图片版 携带方便,查阅方便!~
JAVA正则表达式应用:任意输入一串字符串 如何输入exit退出程序;从输入的字符串中判断是否包含手机号码 正则表达式可以使用" +86| 86 1 d{10}" 如果包含请将其在控制台打印出来 否则输出不包含字符串 ...
Java正则表达式Java正则表达式Java正则表达式Java正则表达式
java正则表达式验证IP地址
正则表达式之道.doc 正则表达式中的特殊字符.doc Java正则表达式详解.doc 正则表达式.ppt JAVA正则表达式--Pattern和Matcher.doc 例子
Java正则表达式应用总结
Java正则表达式详解
java正则表达式.pdfjava正则表达式.pdfjava正则表达式.pdfjava正则表达式.pdfjava正则表达式.pdf
java正则表达式使用例子,代码是Android的
Java正则表达式详解
正则表达式的使用 java正则表达式的使用示例 java正则表达式
java正则表达式详细全面讲解描述
一篇学习Java正则表达式的文章。
Java正则表达式入门介绍课件;Java正则表达式入门介绍课件
网络上搜集到的java正则表达式编程,整理了下做成了PDF格式
java正则表达式使用.docx 资源
Java正则表达式入门介绍.ppt,介绍常用语法规则及使用方式等