替換字符串括號外的所有特殊字符(括號內的不能替換)


 
eg:用-替-換字符串里的特殊字符,並進行切分(括號里的不能替換)
 
String roads = "G6包頭..。?九原收費站((這個是.。--.。?測試)——210國道——幸福南路(備注:車、貨、路線不變,往-返)——210國道(((aa)——210國道(這樣呢)";
 
 
一。思路:1.找到括號的區間范圍
 
          2.判斷匹配內容是否在括號區間內,若在,不替換,若不在,替換 
 
          3.使用StringBuffer的替換,並且保證替換之前和替換之后的長度一致
 
          4.若在括號內的,有特殊字符-的話,替換成*(因為要進行切分,不替換還是會切分掉)
 
 
二。代碼
   
    public void splitFeatureBrackets() {
        String roads = "G6包頭..。?九原收費站((這個是.。--.。?測試)——210國道——幸福南路(備注:車、貨、路線不變,往返)——210國道(((aa)——210國道(這樣呢)";
        log.info("===通行路線總長度==="+roads.length());
        StringBuffer roadsBuff = new StringBuffer(roads);
        //1.獲取通行路線是否包含括號區間
        List list = getBracketsIntervalList(roads);
        Matcher notSpecialMatcher = Pattern.compile(FeatureConst.NOT_SPECIAL_REG_SINGLE).matcher(roads.replaceAll(" +",""));
        if(null!=list&&list.size()>0){
            log.info("===通行路線包含括號區間==="+list.toString());
            //1-1如果包含括號區間,則括號區間里面的值不能被替換
            while(notSpecialMatcher.find()){
                int start = notSpecialMatcher.start();
                log.info("===匹配開始位置==="+start);
                String matcherValue = notSpecialMatcher.group();
                log.info("===匹配的字符串==="+matcherValue);
                //2.判斷該值是否在區間范圍內,若在則不替換,若不在,則替換
                boolean isInIntervalList = IntervalUtil.isInIntervalList(String.valueOf(start),list);
                log.info("===匹配的字符串是否在區間內==="+isInIntervalList);
                if(!isInIntervalList){
                    roadsBuff.replace(start,start+1,"-");
                    log.info("===替換之后的值==="+roadsBuff);
                    log.info("===替換之后的長度==="+roadsBuff.length());
                }else {
                    //2-1.若在括號內的,有特殊字符-的話,替換成*(因為要進行切分,不替換還是會切分掉)
                    if("-".equals(matcherValue)){
                        roadsBuff.replace(start,start+1,"*");
                    }
                }
            }
            log.info("===通行路線替換特殊字符之后==="+roadsBuff);
            String newRoads = roadsBuff.toString().replaceAll("-+","-");
            log.info("===通行路線替換特殊字符之后==="+newRoads);
        }else {
            //1-2.如果不包含,則按之前邏輯,包含特殊字符的值全部替換
            String newRoads = Pattern.compile(FeatureConst.NOT_SPECIAL_REG).matcher(roads.replaceAll(" +","")).replaceAll("-");
            log.info("===通行路線替換特殊字符之后==="+newRoads);
        }
    }

 

 
 
三。得到結果:
 
 
四。其他相關代碼
 
4-1.正則表達式
 
//中英文括號以及括號里面內容正則匹配
public static final String DJYS_STD_FEATURE_REG_BRACKETS = "\\(.*?\\)|\\(.*?\\)";
public static final String NOT_SPECIAL_REG = "[^a-z0-9A-Z\u4e00-\u9fa5()()/]+";//過濾除了數字,字母,中文,(),(),/之外的正則表達式
public static final String NOT_SPECIAL_REG_SINGLE = "[^a-z0-9A-Z\u4e00-\u9fa5()()/]";//過濾除了數字,字母,中文,(),(),/之外的正則表達式

 

4-2.獲取字符串括號的區間集合

    private List getBracketsIntervalList(String str){
        Matcher matcher = Pattern.compile(FeatureConst.DJYS_STD_FEATURE_REG_BRACKETS).matcher(str.replaceAll(" +",""));
        List list = new ArrayList<>();
        //一。獲取括號的區間范圍
        while(matcher.find()){
            //matcher.start()匹配的開始位置(從0開始)
            int start = matcher.start();
            //matcher.end()匹配的結束位置+1(從0開始)
            int end = matcher.end()-1;
            //獲取包含括號的閉區間范圍
            String interval = "[" + start + "," + end + "]";
            list.add(interval);
        }
        return list;
    }

4-3.區間工具類:IntervalUtil

package com.techvalley.djys.api.util;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.List;

public class IntervalUtil {

    /**
     * 判斷data_value是否在interval區間范圍內
     * @author: kangyl17909
     * @date: 2018年7月3日
     * @param data_value 數值類型的
     * @param interval 正常的數學區間,包括無窮大等,如:(1,3)、>5%、(-∞,6]、(125%,135%)U(70%,80%)
     * @return true:表示data_value在區間interval范圍內,false:表示data_value不在區間interval范圍內
     */
    public static boolean isInTheInterval(String data_value,String interval) {
        //將區間和data_value轉化為可計算的表達式
        String formula = getFormulaByAllInterval(data_value,interval,"||");
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
        try {
            //計算表達式
            return (Boolean) jse.eval(formula);
        } catch (Exception t) {
            return false;
        }
    }

    /**
     * 將所有閥值區間轉化為公式:如
     * [75,80)   =》        date_value < 80 && date_value >= 75
     * (125%,135%)U(70%,80%)   =》        (date_value < 1.35 && date_value > 1.25) || (date_value < 0.8 && date_value > 0.7)
     * @param date_value
     * @param interval  形式如:(125%,135%)U(70%,80%)
     * @param connector 連接符 如:") || ("
     */
    private static String getFormulaByAllInterval(String date_value, String interval, String connector) {
        StringBuffer buff = new StringBuffer();
        for(String limit:interval.split("U")){//如:(125%,135%)U (70%,80%)
            buff.append("(").append(getFormulaByInterval(date_value, limit," && ")).append(")").append(connector);
        }
        String allLimitInvel = buff.toString();
        int index = allLimitInvel.lastIndexOf(connector);
        allLimitInvel = allLimitInvel.substring(0,index);
        return allLimitInvel;
    }

    /**
     * 將整個閥值區間轉化為公式:如
     * 145)      =》         date_value < 145
     * [75,80)   =》        date_value < 80 && date_value >= 75
     * @param date_value
     * @param interval  形式如:145)、[75,80)
     * @param connector 連接符 如:&&
     */
    private static String getFormulaByInterval(String date_value, String interval, String connector) {
        StringBuffer buff = new StringBuffer();
        for(String halfInterval:interval.split(",")){//如:[75,80)、≥80
            buff.append(getFormulaByHalfInterval(halfInterval, date_value)).append(connector);
        }
        String limitInvel = buff.toString();
        int index = limitInvel.lastIndexOf(connector);
        limitInvel = limitInvel.substring(0,index);
        return limitInvel;
    }

    /**
     * 將半個閥值區間轉化為公式:如
     * 145)      =》         date_value < 145
     * ≥80%      =》         date_value >= 0.8
     * [130      =》         date_value >= 130
     * <80%     =》         date_value < 0.8
     * @param halfInterval  形式如:145)、≥80%、[130、<80%
     * @param date_value
     * @return date_value < 145
     */
    private static String getFormulaByHalfInterval(String halfInterval, String date_value) {
        halfInterval = halfInterval.trim();
        if(halfInterval.contains("∞")){//包含無窮大則不需要公式
            return "1 == 1";
        }
        StringBuffer formula = new StringBuffer();
        String data = "";
        String opera = "";
        if(halfInterval.matches("^([<>≤≥\\[\\(]{1}(-?\\d+.?\\d*\\%?))$")){//表示判斷方向(如>)在前面 如:≥80%
            opera = halfInterval.substring(0,1);
            data = halfInterval.substring(1);
        }else{//[130、145)
            opera = halfInterval.substring(halfInterval.length()-1);
            data = halfInterval.substring(0,halfInterval.length()-1);
        }
        double value = dealPercent(data);
        formula.append(date_value).append(" ").append(opera).append(" ").append(value);
        String a = formula.toString();
        //轉化特定字符
        return a.replace("[", ">=").replace("(", ">").replace("]", "<=").replace(")", "<").replace("≤", "<=").replace("≥", ">=");
    }

    /**
     * 去除百分號,轉為小數
     * @param str 可能含百分號的數字
     * @return
     */
    private static double dealPercent(String str){
        double d = 0.0;
        if(str.contains("%")){
            str = str.substring(0,str.length()-1);
            d = Double.parseDouble(str)/100;
        }else{
            d = Double.parseDouble(str);
        }
        return d;
    }

    /**
     * 判斷一個數值是否在一個List區間數值內
     * 如:判斷"7"是否在[3,9] [15,23]內
     */
    public static boolean isInIntervalList(String value, List intervalList){
        boolean isInIntervalList;
        for (int i = 0; i < intervalList.size(); i++) {
            isInIntervalList = IntervalUtil.isInTheInterval(value,(String) intervalList.get(i));
            //有匹配,直接返回true
            if(isInIntervalList){
                return true;
            }
        }
        //沒有匹配,返回false
        return false;
    }

}

 

 

 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM