実行環境
- 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("[\\\\/:*?\"<>|]");
文字クラス([])内では、*?|はエスケープが不要(\は要エスケープ)
こちらのほうが、エスケープが少なくて見やすい気がします