正则表达式: 符合一定规则的表达式,专门用于操作字符串;
特点:用一些特点的符号来表示一些代码操作,简化了书写,学习正则表达式,其实就是学这些符号;
好处:简化了对字符串的复杂操作;
弊端:符号越多,正则表达式越长,阅读性差;
常用的基本符号:
[abc]: a,b,或c,即出现的是a,b或c,其他的都不符合规则;
[^abc]: 除了abc其他都可以;
[a-zA-Z]:字符a-z或大写A-Z都可以,包括两头字母;
[a-d[m-p]]:a到d或m-p都行;
. :表示任意字符;
\d:表示数字0-9,
\D:表示非数字,[^0-9];
\w:表示单词字符;a-z,0-9,A-Z_;
\b:表示单词边界;
x?:表示x出现一次或没出现;
x+: 表示至少出现一次;
x*:表示出现0次或多次;
x{n}:表示正好出现N次;
x{n,m}:至少出现n次,至多出现m次;
还有组的概念,用()表示,如果正则表达式中的一部分代表的内容还想被使用,可以先把这个部分括起来,然后用$组号来代表要保留的内容;
常用功能:
① 匹配:String类中的 .matches(regex)方法,匹配符合regex规则的字符串;
②切割:split(regex)方法,注意:如果要使用"."切,正则表达式:"\\.",如果要切"\\",则为"\\\\";
③替换:replaceAll(regex,replacement)
注意:只有有一项不符合正则表达式,判断就会结束,不会再继续判断下去;
代码演示:
/*正则表达式
常用方法:
匹配:String matches(regex)
切割:String split(regex)
替换:String replaceAll(regex,replacement)
*/
class RegexDemo
{
public static void main(String[] args)
{
matchDemo("2334498398239","1[358]\\d{9}");
matchDemo("13842229504","1[358]\\d{9}");
System.out.println("------------匹配----------------");
splitDemo("andy.lili.tony","\\.");//按"."切,注意要用\\.
splitDemo("kdsjfksf kdsfjksdf dkffj kdfj jf"," +");//按 空格切
splitDemo("g:\\java\\code\\day25","\\\\");//按”//“切
splitDemo("dfkdddjfkdaadfzzzzkkkq","(.)\\1+");//按叠词切
System.out.println("------------切割----------------");
replaceDemo("aadddeeeffdoe","(.)\\1+","$1");//将重叠的字符替换成单个字母。iiii>>i 用 $ 获取前一个正则表达式的组。
replaceDemo("andy12;number1388882228384;","\\d{5,}","*");//将字符串中的数字替换成*。
replaceDemo("cdddffeeaadfafkkjkqqccg","(.)\\1+","#");//将叠词提出成#
}
public static void matchDemo(String s,String reg)
{
boolean flag = s.matches(reg);
if(flag)
System.out.println("手机号输入正确");
else
System.out.println("输入号码有误");
}
public static void splitDemo(String s,String reg)
{
String[] arr = s.split(reg);
System.out.println(arr.length);
for(String str:arr)
{
System.out.println(str);
}
}
public static void replaceDemo(String s,String reg,String rp)
{
String ar= s.replaceAll(reg,rp);
System.out.println(ar);
}
}
④用于复杂的获取,要与pattern和matcher配合使用;
操作步骤:
1导入正则包,import java.regex.*;
2将正则表达式封装成pattern对象;
3将正则对象和要操作的字符串关联;
4关联后,获取正则匹配引擎,matcher
5通过引擎,对符合规则的子串进行操作;
代码演示:
import java.util.regex.*;//1
class GetDemo
{
public static void main(String[] args)
{
String s = "adfddfdfflkljkhjjj;; woifieujjfjfslfjdfad;w";
String reg="(.)\\1+";
Pattern p = Pattern.compile(reg);//2
Matcher m = p.matcher(s);//3
while(m.find())//4
{
System.out.println(m.group());
}
}
}
如何判断要选取那种功能进行操作?
① 如果只想知道该字符串是对是错,使用匹配;
② 想要将自己的字符串变成另一个字符串,用替换;
③想要按照指定的方式将字符串变成多个字符串,用切割;
④想要拿到符合需求的子串,使用获取;
练习:
import java.util.*;
class Test
{
public static void main(String[] args)
{
test1();
ipSort();
checkMail();
}
public static void test1()
{
String str = "我我.....我我我我我....我要...要要......要学.....学学学...编编编..编程.程.....程程程...程";
//str=str.replaceAll(str,"我要学编程");
str=str.replaceAll("\\.","");
str=str.replaceAll("(.)\\1+","$1");
System.out.println(str);
}
/*
需求2: 将下边的ip地址段进行地址段顺序的排序。
192.168.1.15 23.48.56.109 10.73.91.18 254.253.252.1 1.23.25.26
思路:
还按照字符自然顺序,只要让它们每一段都是3位即可,
1.按照每一段需要的最多的0进行补齐,那么每一段就会至少保证有3位。
2.将每一段只保留三位,这样所有的ip地址都是每一段3位。
*/
public static void ipSort()
{
String ip = "92.168.1.15 23.48.56.109 10.73.91.18 254.253.252.1 1.23.25.26";
ip = ip.replaceAll("(\\d+)","00$1");
System.out.println(ip);
ip = ip.replaceAll("0+(\\d{3})","$1");
String [] arr = ip.split(" +");
//Arrays.sort(arr);//如果有重复的IP地址并要获取,那么必须用这个
TreeSet<String> ts = new TreeSet<String>();
for(String str:arr)
{
//System.out.println(str);
ts.add(str);
}
for(String s:ts)
{
System.out.println(s.replaceAll("0+(\\d+)","$1"));
}
/*
Iterator<String> it = ts.iterator();
while(it.hasNext())
{
String str = it.next();
str=str.replaceAll("0+(\\d+)","$1");
System.out.println(str);
}
*/
}
/*
需求3:对邮件地址进行校验。这个必须掌握
*/
public static void checkMail()
{
String mail ="asdfas12@sina.com.cn";
//mail = "1@1.1";
String reg = "[a-zA-Z0-9_]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+){1,3}";
//reg = "\\w+@\\w+(\\.\\w+)";//相对不太精确的匹配。
//mail.indexOf("@")!=-1;这种方式不要用。
System.out.println(mail.matches(reg));
}
}
网络爬虫(蜘蛛):
是搜索引擎的原理之一,用以检索网上的信息,如爬邮箱地址,博客,关键字等等;
import java.io.*;
import java.util.regex.*;
import java.net.*;
class RegexTest2
{
public static void main(String[] args) throws IOException
{
getMails_2();
}
//需求2:从网页上获取邮件地址
public static void getMails_2() throws IOException
{
//建立应用层用于连接的端点URLConnection
URL url = new URL("http://www.163.com/");
URLConnection conn = url.openConnection();
//定义读取流,用于读取服务器返回的数据
BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
//定义正则表达式,并获取Pattern对象。
String reg = "\\w+@\\w+(\\.\\w+)+";
Pattern p = Pattern.compile(reg);
while((line = bufIn.readLine())!=null)
{
//获取与某一字符串的关联的正则表达式配适器。
Matcher m = p.matcher(line);
while(m.find())
{
System.out.println(m.group());
}
}
}
/*
需求1:获取指定文档中的邮件地址。
使用获取功能。Pattern Matcher
*/
public static void getMails() throws IOException
{
//http://localhost:8080/myweb/mail.html
BufferedReader bufr = new BufferedReader(new FileReader("mail.txt"));
String line = null;
String reg = "\\w+@\\w+(\\.\\w+)+";
Pattern p = Pattern.compile(reg);
while((line = bufr.readLine())!=null)
{
Matcher m = p.matcher(line);
while(m.find())
{
System.out.println(m.group());
}
}
}
}