java中的正则表达式

来源:互联网 发布:淘宝企业店铺可靠么 编辑:程序博客网 时间:2024/05/14 12:47

运行一遍,其意自辩。

package com.test.regular;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Test {

 public static void main(String[] args) {
  
  String reg1 = "\\d{3}\\s*\\w*\\s*-\\d{8}f\\d+xujie\\d?"; //手动查找符合reg1表达式的字符串部分
  String str1 = "feiworjeiqr025  _ddfafafds -88888883f7xujie33333jklajfiower";
  
  for(int i=0;i<str1.length();i++)
  {
   for(int j=0;j<i;j++)
   {
    String tmp = str1.substring(j, i);
    if(tmp.matches(reg1))
    {
     System.out.println(tmp);
     break;
    }
   }
  }
  
  System.out.println("==================================================================================================");
  
  String reg2 = "\\b\\w{5,7}\\b"; //查找字符数在5-7之间的单词并替换为GOOD
  String str2 = "xiaoxujie is one of the best student in his class, heihei not bad...";
  
  Pattern p = Pattern.compile(reg2);
  Matcher m = p.matcher(str2);
  StringBuffer sb = new StringBuffer();
  while(m.find())
  {
   System.out.println(m.group());
   m.appendReplacement(sb, "GOOD");
  }
  m.appendTail(sb);
  System.out.println(sb.toString());

  System.out.println("==================================================================================================");

  String reg3 = "(0\\d{2}-\\d{8}|0\\d{3}-\\d{7})-([abcde][0-9][a-z0-9A-Z_]|[opq])";//正则中的或关系 "|"
  String str3 = "025-88886666-d8Y";
  System.out.println(str3.matches(reg3));
  
  String reg4 = "(\\w{4}-\\d{2}){3}";//正则中的重复
  String str4 = "abcd-11defg-22huik-33";
  System.out.println(str4.matches(reg4));
  
  System.out.println("==================================================================================================");

  String reg5 = "[^abc]";//正则取反
  System.out.println("a".matches(reg5));
  System.out.println("d".matches(reg5));
  
  System.out.println("<alone>".matches("<a[^>]+>"));
  
 
  System.out.println("==================================================================================================");
  
  String reg6 = "\\b(\\w+)(\\d+)\\b\\s+\\1\\b";
  System.out.println("xu xu".matches(reg6));

  
  System.out.println("==================================================================================================");
 
  String str7 = "员工生活,。";//验证中文字符
  String reg7 = "\\W+";
  System.out.println(str7.matches(reg7));
  System.out.println("hi".matches("\\w+"));
 
 }
}

原创粉丝点击