Jump to content

How to Strip Invalid Characters from Filenames

VOTE
0
  • -
  • +
  Jan Goyvaerts's Photo
Posted Oct 13 2009 11:08 AM

If you want to strip a string of characters that aren't valid in Windows filenames use the following regular expression to accompish the task.

Regular expression

[\\/:"*?<>|]+
Regex options: None
Regex flavors: .NET, Java, Javascript, PCRE, Perl, Python, Ruby

Replacement

Leave the replacement text blank.

Replacement text flavors: .NET, Java, Javascript, PHP, Perl, Python, Ruby

The characters \/:"*?<>| are not valid in Windows filenames. These characters are used to delimit drives and folders, to quote paths, or to specify wildcards and redirection on the command line.

We can easily match those characters with the character class [\\/:"*?<>|]. The backslash is a metacharacter inside character classes, so we need to escape it with another backslash. All the other characters are always literal characters inside character classes.

We repeat the character class with a + for efficiency. This way, if the string contains a sequence of invalid characters, the whole sequence will be deleted at once, rather than character by character. You won’t notice the performance difference when dealing with very short strings, such as filenames, but it is a good technique to keep in mind when you’re dealing with larger sets of data that are more likely to have longer runs of characters that you want to delete.

Since we just want to delete the offending characters, we run a search-and-replace with the empty string as the replacement text.

Cover of Regular Exp<b></b>ressions Cookbook
Learn more about this topic from Regular Expressions Cookbook.  This cookbook provides more than 100 recipes to help you crunch data and manipulate text with regular expressions. With recipes for popular programming languages such as C#, Java, Javascript, Perl, PHP, Python, Ruby, and VB.NET, Regular Expressions Cookbook will help you learn powerful new tricks, avoid language-specific gotchas, and save valuable time with this library of proven solutions to difficult, real-world problems.
Learn More Read Now on Safari







0 Alternative Solutions | 0 Comments

filter by: