正则只替换URL字符串里面的汉字部分



URL为 http://192.168.1.1:8080/resources/电话.xls
如果使用 URLEncoder.encode 将会把冒号等一块给替换了
http%3A%2F%2F192.168.1.1%3A8080%2Fresources%2F%E7%94%B5%E8%AF%9D.xls

这并不是我们需要的,我们只希望替换编码里面中文的部分,这里给出了解决方法,很简单

  1. package log;

  2. import java.io.UnsupportedEncodingException;
  3. import java.net.URLEncoder;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;

  6. /**
  7.  * 正则替换字符串里面的汉字部分。
  8.  * 
  9.  * @author 赵学庆 www.java2000.net
  10.  */
  11. public class URLEncoderHZ {
  12.   public static void main(String[] args) throws Exception {
  13.     String str = "http://192.168.1.1:8080/resources/电话.xls";
  14.     System.out.println(encode(str, "UTF-8"));
  15.   }

  16.   private static String zhPattern = "[/u4e00-/u9fa5]+";

  17.   /**
  18.    * 替换字符串卷
  19.    * 
  20.    * @param str 被替换的字符串
  21.    * @param charset 字符集
  22.    * @return 替换好的
  23.    * @throws UnsupportedEncodingException 不支持的字符集
  24.    */
  25.   public static String encode(String str, String charset) throws UnsupportedEncodingException {
  26.     Pattern p = Pattern.compile(zhPattern);
  27.     Matcher m = p.matcher(str);
  28.     StringBuffer b = new StringBuffer();
  29.     while (m.find()) {
  30.       m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
  31.     }
  32.     m.appendTail(b);
  33.     return b.toString();
  34.   }
  35. }


运行结果

http://192.168.1.1:8080/resources/%E7%94%B5%E8%AF%9D.xls 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值