LoginSignup
1
2

More than 5 years have passed since last update.

Apex(ユーティリティ)

Last updated at Posted at 2017-03-02

SJISでのバイト数を取得する

/*
 * SJISでのバイト数(全角2、半角1)を算出する
 * (String.length()は全角 半角を区別しない)
 */     
private static Integer getSJISLength(String s) {
    Integer zenkakuLength = s.replaceAll('[\\uFF61-\\uFF9F\\u0020-\\u007E]', '').length();
    Integer hankakuLength = s.length() - zenkakuLength;
    return zenkakuLength * 2 + hankakuLength;
}

HTML文字列をPlainテキストに変換する

/*
 * HTML文字列をPlainテキストに変換する
 *  html HTML 文字列
 *  戻り値 Plainテキスト
 */
public static String convertToHtmlToText(String html){
    String htmlPattern = '<(?i).*?>';
    String breakPattern = '(?i)<br\\s*/?>';  // matches <br>, <BR>, <br/>, <br />, <br   />, etc.
    String whitespacePattern = '\\s+';

    String workingText = html!=null ? html : '';

    // replace all HTML break tags with the newLine character
    Pattern lineBreaks = Pattern.compile(breakPattern);
    Matcher matchedLineBreaks = lineBreaks.matcher(workingText);
    workingText = matchedLineBreaks.replaceAll(CommonUtility.CRLF);

    //plainテキストに変換した時に見栄えがよくなるようにする
    workingText = workingText.replaceAll('</li>', CommonUtility.CRLF);
    workingText = workingText.replaceAll('<li>', '- ');

    // HTMLタグの削除
    Pattern htmlTags = Pattern.compile(htmlPattern);
    Matcher matchedHTML = htmlTags.matcher(workingText);
    workingText = matchedHTML.replaceAll('');

    //urlEncodeしてスペースと改行を補正する
    workingText = EncodingUtil.urlEncode(workingText, 'UTF-8');
    workingText = workingText.replaceAll('%C2%A0', '+'); //space
    workingText = workingText.replaceAll('%3Cbr%3E', '%0D%0A'); //carriage return
    workingText = EncodingUtil.urlDecode(workingText, 'UTF-8');   

    return workingText;
}        

日付から日本語の曜日を返す

private static Map<String, String> JPN_YOUBI = new Map<String, String>{'Monday'=>'月', 'Tuesday'=>'火', 'Wednesday'=>'水', 'Thursday'=>'木', 'Friday'=>'金', 'Saturday'=>'土', 'Sunday'=>'日' };

/*
 * 日付から日本語の曜日を返す
 *  dt 対象の日付時間
 */ 
public static String getJapaneseYoubi(Datetime dt){
    return JPN_YOUBI.get(dt.format('EEEE'));    
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2