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.

3
  • Btw, you have a compiler error, invalid escape sequence. Commented Jan 23, 2013 at 13:38
  • The folder name is from server side in a JSON Commented Jan 23, 2013 at 13:39
  • @Arslan: Not in the folder name, in the ReservedChars string. Commented Jan 23, 2013 at 13:43

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Why have you escaped everything in character class?
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

Comments

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.

Comments

0

Try this :

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

It will replace all non alphanumeric characters with underscore

1 Comment

But I need to replace only specific set of characters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.