java正则表达式

正则表达式是很常见的。但是也是很容易出错的。
  所以,整理了写 Java正则表达式的方法。
 
1、正则初体验:pattern(模式)。split(分割_成数组)。compile(编译)、matcher(匹配器)
//  获取需要正则的主体
  String str2 = "ceponline@yahoo.com.cn";
//  创建模型Pattern,再编写compile正则表达式语法
  Pattern pattern5 = Pattern.compile(".+@.+\..+?");
//  使用正则模型去匹配matcher需要正则的主体
  Matcher matcher5 = pattern5.matcher(str2);
//  打印验证正则是否正确
System.out.print("
" + matcher5.matches());       
 
2、正则表达式语法:(在compile中的字符串)
  .+ 表示任何不为空的    \.  表示转译为 .              ^开头       $结尾 
  ? 表示为懒惰模式。匹配到第一个满足的就停止               * :0到无穷          + :1到无穷                
  d 数字:[0-9]       D 非数字:[^0-9]      w数字和字母[a-zA-Z0-9]      W 非数字和字母 [^a-zA-Z0-9]
  • 在一些语言里,"\"的意思是"在正则表达式里插入一个反斜杠。"但是在Java里,"\"的意思是"要插入一个正则表达式 的反斜杠,
  • 那么java正则表达式就应该是"\w+"。如果要插入一个反斜杠,那就得用"\\"。
  • java像换行,跳格之类的只用一根反斜杠" "。
 
3、正则实战:
Pattern pattern = Pattern.compile("[, |]+");
String[] strs = pattern.split("Java Hello World Java,Hello,,World|Sun");
for (int i = 0; i < strs.length; i++) {
    System.out.print("	" + strs[i]);
}
输出结果 为: Java      Hello     World     Java     Hello     World     Sun
 
验证邮箱地址:
String str2 = "ceponline@yahoo.com.cn";
Pattern pattern5 = Pattern.compile(".+@.+\..+?");
Matcher matcher5 = pattern5.matcher(str2);
System.out.print("
" + matcher5.matches());             //返回 布尔值
 
去除html标记:
Pattern pattern6 = Pattern.compile("<.+?>");
Matcher matcher6 = pattern6.matcher("<a href="index.html">主页</a>");
String string = matcher6.replaceAll("");
System.out.println("
" + string);                 
 
// 截取url
Pattern pattern8 = Pattern.compile("<http://.+?>");
Matcher matcher8 = pattern8.matcher("dsdsds<http://www.baidu.com/>fdf");
if (matcher8.find()) {
System.out.println(matcher8.group());                   // 返回匹配的字符串
}
 
简单的 example:
String str = "正则表达式 Hello World,正则表达式 Hello World ";
str.replace("hello" , "我要替换hello")
 
筛选数字
    public Double regexGetMath(String matcher) {
        Pattern pattern = Pattern.compile("[^0-9/.]");
        Matcher match = pattern.matcher(matcher);
        String getStr = match.replaceAll("");
        Double getNum = Double.parseDouble(getStr);
        return getNum;
    }
 
筛选字符串
      public String regexGetLetterLow(String matcher) {
        Pattern pattern = Pattern.compile("[^a-zA-Z]");
        Matcher match = pattern.matcher(matcher);
        String getStr = match.replaceAll("").toLowerCase();
        return getStr;
    }
原文地址:https://www.cnblogs.com/zhongmeizhi/p/6306933.html