------- android培训、java培训、期待与您交流! ----------
正则表达式:符合一定规则的表达式
作用:用于专门操作字符串。可以简化对只付出的复杂操作。
特点:用于一些特定的符号来表示一些代码操作。简化书写。
弊端:符号定义越多,正则越长,阅读性越差。
例子:判断一个字符串是否符合QQ号的规则
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
String reg = "[1-9]\\d{4,14}";
boolean b = str.matches(reg);
if(b){
System.out.println("正确");
}else{
System.out.println("错误");
}
}
}
例子:输入一个字符串,去除连续的字符,只保留1个
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
String reg = "(.)\\1+";
String s = str.replaceAll(reg, "$1");
System.out.println(s);
}
}
例子:治疗口吃,我我我我....要要....学学学....编...编...程程..程 把这句话编程 我要学编程
public class Test {
public static void main(String[] args){
String str = "我我我我....要要....学学学....编...编...程程..程";
String reg = "(\\.)+";
String reg2 = "(.)\\1+";
str = str.replaceAll(reg,"");
str = str.replaceAll(reg2,"$1");
System.out.println(str);
}
}
例子:ming tian fang jia 获取4个字母组成的
import java.util.regex.*;
public class Test {
public static void main(String[] args){
String str = "ming tian fang jia";
String reg = "(\\b[a-z]{4}\\b)+";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
while(m.find()){
System.out.println(m.group());
}
}
}
例子:获取外网IP和IP所属地
public class Test{
public static void main(String[] args){
BufferedReader br = null;
ArrayList<String> s = new ArrayList<String>();
try{
URL u = new URL("http://www.ip.cn/");
URLConnection url = u.openConnection();
br = new BufferedReader(new InputStreamReader(url.getInputStream(),"UTF-8"));
String str = null;
String reg = "当前 IP:<code>[0-9\\.]+</code>";
String str2 = null;
String str3 = null;
String reg3 = "来自:.+</p><p>";
while((str = br.readLine())!=null){
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
while(m.find()){
str2 = m.group();
}
p = Pattern.compile(reg3);
m = p.matcher(str);
while(m.find()){
str3 = m.group();
}
}
String reg2 = "[0-9].+[0-9]";
Pattern p = Pattern.compile(reg2);
Matcher m = p.matcher(str2);
while(m.find()){
System.out.print("外网IP:"+m.group());
}
reg3 = "[^</>p来自:]";
p = Pattern.compile(reg3);
m = p.matcher(str3);
while(m.find()){
s.add(m.group());
}
System.out.print("\n地址:");
for(String ss : s){
System.out.print(ss);
}
}
catch(IOException e){
throw new RuntimeException("读入文件出错");
}
}
}