0
0

More than 1 year has passed since last update.

Windowsのファイル名で禁止されている記号を置換する

Posted at

実行環境

  • Eclipse IDE for Enterprise Java Developers
  • OS: Windows 10
  • Java version: 11.0.9

コード

Main.java
    public static void main(String[] args) {
        // Windowsでファイル名として禁止されている文字は\/:?"<>|
        String src = "\\_/_:_*_?_\"_<_>_|.txt";
        Pattern illegalFileNamePattern = Pattern.compile("\\\\|/|:|\\*|\\?|\"|<|>|\\|");
        String fileName = illegalFileNamePattern.matcher(src).replaceAll("-");
        System.out.println("src        :"+src);      // \_/_:_*_?_"_<_>_|.txt
        System.out.println("fileName   :"+fileName); // -_-_-_-_-_-_-_-_-.txt
    }

ポイント

Pattern illegalFileNamePattern = Pattern.compile("\\\\|/|:|\\*|\\?|\"|<|>|\\|");

\\\\
↑ダブルクオート内でバックスラッシュ(\)を使いたい場合は\\
正規表現(括弧)内でバックスラッシュ(\)をエスケープするためにバックスラッシュ(\\)が必要
結果バックスラッシュ4つになる
\\*
\\?
↑*と?はメタ文字なので、メタ文字として使われないようにエスケープする
\"
↑ダブルクオートはそのままだと、comple("の文字列の終わりを表すダブルクオートになるので、エスケープする
\\|
↑パイプ(|)はメタ文字のため、*や?と同様にエスケープする

文字クラスを使った書き方

Pattern illegalFileNamePattern = Pattern.compile("[\\\\/:*?\"<>|]");

文字クラス([])内では、*?|はエスケープが不要(\は要エスケープ)
こちらのほうが、エスケープが少なくて見やすい気がします

0
0
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
0
0