4

I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file

e.g

String folder = "ArslanFolder 20/01/2013";

So I want to remove these characters with "_"

Here are characters

private static final String ReservedChars = "|\?*<\":>+[]/'"; 

What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.

Rohit Jain
  • 203,151
  • 43
  • 392
  • 509
Arslan Anwar
  • 18,646
  • 19
  • 75
  • 105

4 Answers4

16

Use this code:

String folder = "ArslanFolder 20/01/2013 ? / '";
String result = folder.replaceAll("[|?*<\":>+\\[\\]/']", "_");

And the result would be:

ArslanFolder 20_01_2013 _ _ _

you didn't say that space should be replaced, so spaces are there... you could add it if it is necessary to be done.

Sufian
  • 6,225
  • 16
  • 65
  • 116
Kent
  • 181,427
  • 30
  • 222
  • 283
1

I used one of this:

String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");

See this link: Replace special characters

Community
  • 1
  • 1
0

Try this :

replaceAll("[\\W]", "_");

It will replace all non alphanumeric characters with underscore

jlordo
  • 36,534
  • 6
  • 55
  • 79
Renjith
  • 3,187
  • 17
  • 39
0

This is correct solution:

String result = inputString.replaceAll("[\\\\|?\u0000*<\":>+\\[\\]/']", "_");

Kent answer is good, but he isnt include characters NUL and \.

Also, this is a secure solution for replacing/renaming text of user-input file names, for example.