【Java/Regular Expression】在Java中使用正则表达式处理文本的几种典型模式(验证、查找和更替)

本文不是讲述正则表达式如何写的,如果想知道这一点,请自行购买以下书籍阅读:

 注意:作者的这本书真是绝了,言简意赅,直中要害,相对而言市面上的同类书籍显得超沉超重,废话较多。但是,这作者的这一本书值得花钱,因为他用心去写了;但他的其它书就不一定了,我个人觉得是续貂之作。各位看官请明辨!

本文是讲述Java里如何使用正则表达式帮助我们完成字符串验证、查找和更替业务的,代码如下:

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式常见使用案例
 * @author heyang
 *
 */
public class RegExp {
    /**
     * 验证例子,使用Pattern.matches
     * 看一个字符串是否符合某个模式,常用于英数字验证、号码验证、汉字平片假名验证等 
     * @param code
     * @return
     */
    private static boolean verify(String code) {
        final String patternStr = "\d{6}";
        return Pattern.matches(patternStr, code);
    }
    
    /**
     * 验证例子二,使用string.matches
     * @param cmd
     * @return
     */
    private static boolean isAllowed3Cmd(String cmd) {
        return cmd.matches("^(?i)(create|delete|listall)$");
    }
    
    /**
     * 更替例子,将符合模式的字符串替换成别的字符串
     */
    private static void replaceAll() {
        String str = "10元 1000人民币 10000元 100000RMB";
        String newstr = str.replaceAll("(\d+)(元|人民币|RMB)", "$1圆");
        System.out.println(newstr);
    }
    
    /**
     * 查找例子
     * 本例只查找位置,不进行处理
     */
    private static void search() {
        Pattern pattern = Pattern.compile("m(o+)n", Pattern.CASE_INSENSITIVE);
        
        Matcher matcher=pattern.matcher("Sun Earth moon mooon Mon mooooon Mooon Mars");
        while(matcher.find()) {
            System.out.println(String.format("%s (%d~%d)", matcher.group(0),matcher.start(),matcher.end()));
        }
    }
    
    /**
     * 查找符合模式的部分进行更替
     */
    private static void findandReplace() {
        String rawSql="select * from a=:av and b=:bv and c=:cv and d = : dv";
        System.out.println("rawSql="+rawSql);
        
        // 模拟输入的条件
        Map<String,String> map=new HashMap<>();
        map.put("av", "1");
        //map.put("bv", "2");// 被屏蔽的表示此条件未输入
        map.put("cv", "3");
        map.put("dv", "4");
        
        Pattern pattern=Pattern.compile("((\w+)\s*[=]\s*)([:]\s*(\w+))");
        Matcher matcher=pattern.matcher(rawSql);
        boolean found=matcher.find();
        
        StringBuilder sb=new StringBuilder();
        while(found) {
            String value=matcher.group(4);
            
            if(map.containsKey(value)) {
                matcher.appendReplacement(sb, matcher.group(1)+map.get(value));
            }else {
                matcher.appendReplacement(sb, "1=1");
            }
            
            found=matcher.find();
        }
        matcher.appendTail(sb);
        
        String finalSql=sb.toString();
        System.out.println("finalSql="+finalSql);
    }
    
    public static void main(String[] args) {
        System.out.println(String.format("601857 %s a stock code.",verify("601857")?"is":"isn't"));
        
        String cmd="Create";
        System.out.println(String.format("%s %s a legal command.",cmd,isAllowed3Cmd(cmd)?"is":"isn't"));
        
        search();
        
        replaceAll();
        
        findandReplace();
    }
}

输出:

601857 is a stock code.
Create is a legal command.
moon (10~14)
mooon (15~20)
Mon (21~24)
mooooon (25~32)
Mooon (33~38)
10圆 1000圆 10000圆 100000圆
rawSql=select * from a=:av and b=:bv and c=:cv and d = : dv
finalSql=select * from a=1 and 1=1 and c=3 and d = 4

END

原文地址:https://www.cnblogs.com/heyang78/p/15336511.html