正则表达式

正则表达式:就是用操作字符串数据的规则表达式。

规则:就是用一些符号组成,每个符号都代表着特有的含义。
其实这些符号相当于对应着底层一段代码。对外提供符号是简化了操作。
具体符号查看API文档。。

弊端:必须要先学习这些符号。符号多了,阅读性会较差。

正则表达式对字符串的常见操作:
1,匹配。
使用的是String类中的matchers方法。
2,切割。
使用的是String类中的split方法。
3,替换。
使用的是String类中的replaceAll方法。
4,获取。

将匹配的规则的内容获取出来。
需要 使用的是正则表达式对象。Pattern
1,先将正则表达式编译成Pattern对象。
2,通过Pattern对象的matcher方法获取Matcher匹配器对象。
3,通过匹配器对象的方法,将正则规则作用到字符串上以便于操作。
获取实际例子:
public static void getDemo() {

String str = "da jia zhu yi la ,yao pai wei dian ying la !";

String reg = "\\b[a-z]{3}\\b";//三个字母组成的单词都读取出来

//正则规则被编译成patten对象
Pattern p = Pattern.compile(reg);
//通过正则对象的方法matcher和字符串关联获取匹配器
Matcher m = p.matcher(str);
//使用匹配器的方法对字符串进行操作
while(m.find()){
System.out.println(m.start()+"--"+m.group()+"--"+m.end());
}

}


实际例子:
1,网页爬虫:
* 需求:就是获取指定文件中的特定信息,比如邮箱地址
* 思路:
* 1,读取文件。
* 2,获取文件中的每一行字符串,
* 4,对该行字符串中的特定信息进行规则的匹配,将符合的规则都获取出来进行存储。
//1,获取网络中的
public static void getMailsByNet() throws IOException {

URL url =new URL("http://www.sina.com");
BufferedReader bufr = new BufferedReader(newInputStreamReader(url.openStream()));

String line = null;
String mail_reg = "\\w+@\\w+(\\.\\w+)+";
Pattern p = Pattern.compile(mail_reg);
while ((line=bufr.readLine())!=null){
Matcher m = p.matcher(line);
while(m.find()){
System.out.println(m.group());
}
}
}
//2,获取指定文件中的邮箱地址
public static void getMails() throws IOException{
BufferedReader bufr = new BufferedReader(new FileReader(""));

String line = null;
String mail_reg = "\\w+@\\w+(\\.\\w+)+";
Pattern p = Pattern.compile(mail_reg);
while ((line=bufr.readLine())!=null){
Matcher m = p.matcher(line);
while(m.find()){
System.out.println(m.group());
}
}
}
}
2,口吃:
* 我我我...我我..我要...要要..要要..学.学...学学学.编.编编编...程..程程
* 要求:将该字符串变成 我要学编程。

* 思路:
* 1,先去掉所有.;替换
* 2,叠词变成一个。
public static void Test_1() {

String str ="我我我...我我..我要...要要..要要..学.学...学学学.编.编编编...程..程程";

str= str.replaceAll("\\.+", "");
System.out.println(str);

str = str.replaceAll("(.)\\1+","$1");
System.out.println(str);
}

3,IP排序问题:
*192.108.90.34 10.10.10.10 5.5.5.5 30.107.100.5

* 对ip地址字符串中的ip地址进行排序,按照ip的分类顺序。

public static void Test_2() {

String ip = "192.108.90.34 10.10.10.10 5.5.5.5 30.107.100.5";

ip = ip.replaceAll("(\\d+)","00$1");
System.out.println(ip);

ip = ip.replaceAll("0*(\\d{3})", "$1");
System.out.println(ip);

String[] ips = ip.split(" +");
Arrays.sort(ips);
for(String i: ips){
System.out.println(i.replaceAll("0*(\\d+)", "$1"));
}

}

3,邮件校验:

public static void Test_3() {

String mail = "abc23@sina.com.cn";

String reg ="[a-zA-Z_0-9]+@[a-zA-Z0-9]+(\\.[a-zA-Z]{2,}){1,3}";


// reg = "\\w+@\\w+(\\.\\w+)+";笼统匹配
boolean b = mail.matches(reg);

System.out.println(mail+"::"+b);

}