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
  • 209,639
  • 45
  • 409
  • 525
Arslan Anwar
  • 18,746
  • 19
  • 76
  • 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,405
  • 16
  • 66
  • 120
Kent
  • 189,393
  • 32
  • 233
  • 301
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
1

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.

0

Try this :

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

It will replace all non alphanumeric characters with underscore

jlordo
  • 37,490
  • 6
  • 58
  • 83
Renjith
  • 3,274
  • 19
  • 39