正则表达式有如下几种常规应用:
A,格式匹配,如邮箱信息。
B,隐藏某些特殊的信息
C,删除连续出现的多余字符
D,特别复杂的格式排序
自己对几种比较有针对性的特点总结如下代码:
- import java.util.regex.*;
- import java.util.*;
- public class PatternRecognizition {
- public static void main(String[] args) {
- // TODO 自动生成的方法存根
- String name = "192.168.1.254 102.49.23.20 10.10.10.10";
-
- print(sortIpAddress(name));
- }
-
- public static void checkMailFormat(String str) {
-
- String regx = "[a-zA-Z0-9_.]{6,}@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+" ;
- if(str.matches(regx)) {
- System.out.println("Mail Format is correct.");
- } else {
- System.out.println("Mail Format is incorrect.");
- }
-
- }
-
- public static String hideMailCount(String str) {
-
- String regx = "[a-zA-Z0-9_.]{6,}@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+" ;
- str = str.replaceAll(regx,"##########");
- return str;
- }
-
- public static String deleteRepeatCharacter(String str) {
-
- String regx = "(.)\\1+";
-
- str = str.replaceAll(regx, "$1");
-
- return str;
- }
-
- public static String sortIpAddress(String str) {
-
- String regx = null;
- String list[];
- StringBuilder strbuild = new StringBuilder();
- //insert 00 in front of the digital.
- regx = "(\\d+)";
- str = str.replaceAll(regx,"00$1");
- regx = "0*(\\d{3})";
- str = str.replaceAll(regx,"$1");
-
- list = str.split(" +");
- Arrays.sort(list);
- for(String e: list) {
- strbuild.append(e+" ");
- }
- regx = "0*(\\d+)";
- str = strbuild.toString().replaceAll(regx,"$1");
- return str;
- }
-
- public static void print(Object e) {
- System.out.println(e);
- }
- }
复制代码
|
|