正則只替換URL字符串裏面的漢字部分(轉載CSDN)

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();
  }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章