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

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


package log;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


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


private static String zhPattern = "[\u4e00-\u9fa5]+";


/**
* 替换字符串卷
*
* @param str 被替换的字符串
* @param charset 字符集
* @return 替换好的
* @throws UnsupportedEncodingException 不支持的字符集
*/
public static String encode(String str, String charset) throws UnsupportedEncodingException {
Pattern p = Pattern.compile(zhPattern);
Matcher m = p.matcher(str);
StringBuffer b = new StringBuffer();
while (m.find()) {
m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
}
m.appendTail(b);
return b.toString();
}
}


运行结果

http://192.168.1.1:8080/resources/%E7%94%B5%E8%AF%9D.xls
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值