import java.util.*;
class RegexTest
{
//-------------------------------------------
/*
需求:
将下列字符串转换成:我要学编程
到底用四种功能中的哪一个呢?或者哪几个呢?
思考方式:
1.如果只想知道该字符是对是错,匹配。
2.想要将已有的字符串变成另一个字符串,替换。
3.想要按照指定的方式将字符串变成多个字符串,切割。 获取规则以外的子串。
4.想要拿到符合需求的字符串子串,获取。 获取符合规则的子串。
*/
public static void test_1()
{
String str = "我我...我我...我要..要要..要要...学学学...学学...编编编...编程..程.程程...程...程";
//将已有的子串变成另一个字符串,使用替换功能。
str = str.replaceAll("\\.+","");
str = str.replaceAll("(.)\\1+","$1");
System.out.println(str);
}
//-------------------------------------------
/*
192.168.1.111 102.49.23.13 10.10.10.10 2.2.2.2 8.109.90.30
将ip地址进行地址段顺序的排序
思路:
还按照字符串自然顺序,只要让它们每一段都是3位即可。
步骤:
1.按照每一段需要的最多补0进行补齐,那么每一段就会至少保证有3位
2.将每一段只保留3位。这样,所以的Ip址都是每一段3位。
3.排序。用TreeSet集合。
4.去掉多余的0
*/
public static void sortIP()
{
String ip = "192.168.1.111 102.49.23.13 10.10.10.10 2.2.2.2 8.109.90.30";
ip = ip.replaceAll("(\\d{1,3})","00$1");
//System.out.println(ip);
ip = ip.replaceAll("0*(\\d{3})","$1");
//System.out.println(ip);
String[] arr = ip.split(" +");
TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder());
for(String s : arr)
{
ts.add(s);
}
for(String s : ts)
{
ip = s.replaceAll("0*(\\d+)","$1");
System.out.println(ip);
}
}
//-------------------------------------------
/*
需求:对邮箱地址进行检验。
*/
public static void checkMail()
{
//对 新浪 邮箱地址进行检验。
//String mail = "abc12@sina.com";
//String reg = "[a-zA-Z0-9_]+@sina\\.com";
//System.out.println(mail.matches(reg));
//对邮箱地址进行检验。
String mail = "ab_c12@sohu.com.cn";
String reg = "[a-zA-Z0-9_]+@[a-z]+(\\.[a-z]+)+";
System.out.println(mail.matches(reg));
}
//-------------------------------------------
public static void main(String[] args)
{
//test_1();
//sortIP();
checkMail();
}
}
day25/RegexTest.java
最新推荐文章于 2023-01-12 00:21:53 发布