正则表达式;

前端之家收集整理的这篇文章主要介绍了正则表达式;前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package regex; /* * 正则表达式; * 用于操作字符串数据 * 通过一些特定的符号来体现的. * 掌握正则表达式,需要学习一些符号. * * 简化,但阅读性差: * * 主要四个用法 * 匹配:matches()方法 * 切割:split()方法 * 替换:replaceAll()方法 * 获取/查找:java.util.regex类.Pattern接口和java.util.regex.Matcher类的 * * 将正则规则进行对象的封装 * Pattern p=Pattern.compile("a*b"); * 匹配器 * Matcher m=p.matcher("aaaab"); * 匹配器的方法进行操作. * boolean b=m.matches(); * * */ public class Regex { public static void main(String[] args) { /* * 需求:定义一个功能对QQ号进行校验 * 要求:长度5-10,只能是数字.0不能开头 */ String qq="12413414"; // checkQQ(qq); String regex="[1-9][0-9]{4,14}";//正则表达式 boolean b=qq.matches(regex); System.out.println(qq+":"+b); } public static void checkQQ(String qq) { int len = qq.length(); if (len >= 5 && len <= 15) { if (!qq.startsWith("0")) { try { long l = Long.parseLong(qq); System.out.println("正确"); } catch (NumberFormatException e) { System.out.println(qq + ":含有非法字符"); } } } else { System.out.println(qq + "长度错误"); } } } package regex; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexTest { public static void main(String[] args) throws IOException { List<String> list=testweb(); for (String string : list) { System.out.println(string); } } public static List<String> testweb() throws IOException { //见面爬虫:其实就是一个程序用于在互联网中获取符合指定规则的数据。 //源 // BufferedReader bufr=new BufferedReader(new FileReader("c:\\mail.html")); URL url=new URL("http://192.168.10.254:80/*"); BufferedReader bufin=new BufferedReader(new InputStreamReader(url.openStream())); //规则 String regex="\\w+@\\w+(\\.\\w)+"; List<String> list=new ArrayList<String>(); //匹配器 Pattern p=Pattern.compile(regex); String line=null; while((line=bufin.readLine())!=null){ Matcher m=p.matcher(line); while(m.find()){ list.add(m.group()); } } return list; } public static void testmail() { String mail="wwwsaa@sina.com.cn"; String regex="[a-zA-Z0-9_]+@[a-zA-Z0-9]+([a-zA-Z]{1,3})+"; boolean b=mail.matches(regex); System.out.println(mail+":"+b); } public static void testip() { String ip="120.7.8.5 127.1.2.2 10.1.2.3"; //补0 ip=ip.replaceAll("(\\d+)","00$1"); //保留3位 ip=ip.replaceAll("0*(\\d{3})","$1"); //切割 String[] ips=ip.split(" +"); //对象排序 TreeSet<String> ts=new TreeSet<String>(); for(String inip:ips){ ts.add(inip); } //打印 for(String ipout:ts){ System.out.println(ipout.replaceAll("0*(\\d+)","$1")); } } public static void test1() { String str="我我....我我...学学学....学学学...习习习...习习..编编..编编编编...编编..程程..程程程程..程程"; str=str.replaceAll("\\.+",""); str=str.replaceAll("(.)\\1+","$1"); System.out.println(str); } } 原文链接:https://www.f2er.com/regex/363038.html

猜你在找的正则表达式相关文章