項目中用過的正則

一、獲取url參數正則表達式

 /**
     * 獲取uri參數值
     *
     * @param string
     * @param name
     * @return
     */
    public static String getUriParamValue(String string, String name)
    {
        if(TextUtils.isEmpty(string) || string.indexOf("?") <= 0) return "";

        Pattern pattern = Pattern.compile("(" + name +"=([^&]*))", Pattern.CASE_INSENSITIVE);
        Matcher m = pattern.matcher(string);
        if (m.find())
        {
//            String text0 = m.group(0);
//            String text1 = m.group(1);
            String value = m.group(2);
            try {
                return URLDecoder.decode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return value;
            }
        }
        return "";
    }

 

二、域名切換json

/**
     * 域名切換
     *
     * @param url
     * @return
     */
    public static String replaceUrlHost(String url, boolean replace)
    {
        if(TextUtils.isEmpty(url) || !replace) return url;

        String urlPattern = "^(https?://)(.*.)haiziwang(.com)(/.*)?$";
        Pattern pattern = Pattern.compile(urlPattern);
        Matcher matcher = pattern.matcher(url);
//     System.out.println(matcher.find());
        return matcher.replaceAll("$1$2newhost$3$4");
    }

 

三、json中獲取字段url

private static String getxxx(String str)
	{
		
		Pattern pattern = Pattern.compile("(" + "\"floatinfo\"\\:\\{[^\\}.]*\\})", Pattern.CASE_INSENSITIVE);
		Matcher m = pattern.matcher(str);
		if (m.find())
		{
			String value = m.group(1);
			return value;
		}
		
		return "";
	}

四、刪除接口文檔中的註釋,註釋多是//或者()或者()形式存在.net

     須要兩個正則表達式,執行兩次:code

     第一次 (?<!:)//.*$  排除http://,(?<!exp)是不以exp開頭接口

     第二次 [(|\(].*$  中文圓括號或者英文圓括號中的註釋文檔

     能夠將兩次合併成一個表達式,把他們當作分組,用|鏈接連個分組get

     ([(|\(].*$)|((?<!:)//.*$)string

五、寫接口時常常須要copy參數,如今用正則替換:  域名

參數:將換行替換成逗號+空格   \s*$\r\n 替換成,  

參數註釋:^  替換成 * @param

相關文章
相關標籤/搜索