Regex.Replace statement to get rid of non-permitted characters in file name

Hi, anyone can post the Regex.Replace statement to get rid of characters which are non permitted in filenames? I know there are existing posts to get rid of All special characters, but I want to keep those special characters which are still permitted in filenames

1 Like

Can we see any samples??

I don’t have an existing workflow, this is just for utility purposes when I need to use it…

E.g. I have an email subject “Work event on 20/5/2020”, I want to save the attachment as “Work event on 20/5/2020_filename1.docx” …

except that I can’t do this because slashes are not permitted in filenames.

Well I know that there are other characters which are not permitted and I can’t remember them all, I just need a Regex.Replace statement that I can use to get rid of these


You are trying to avoid the error message I got “illegal characters found” or something like that when trying to save a file.

Try using an assign activity after using the Regex where:

INSERTVARIABLE = System.Text.RegularExpressions.Regex.Replace(INSERTVARIABLE, “[^a-z A-Z 0-9]”, “”)

Replace “INSERTVARIABLE” with your variable and done :slight_smile:

This will clean all the characters except for a-z or A-Z or 0-9 ranges.


I had this problem even when I didnt have a ‘dirty’ variable. I can make it a habit to clean my variables when making file names.

I hope this works for you.

1 Like

Hi, I found this regex elsewhere but I need to adapt it to fit the permitted characters in the filename. For example, brackets are special characters but still permitted in filename. And there are a few other special characters that are allowed. How do you modify this regex so that these special characters are included?

I.e. Any Unicode except NUL , \ , / , : , * , " , < , > , |

1 Like

Just add some () and a space to the brackets. Like this:
INSERTVARIABLE = System.Text.RegularExpressions.Regex.Replace(INSERTVARIABLE, “[^a-z A-Z 0-9 ()]”, “”)

This will get you out of a pinch but if you find something that is LIKELY to be in the filename AND its missing then add it into the above.

See below image for BEFORE and AFTER write line results:

Where the assign is:
System.Text.RegularExpressions.Regex.Replace(str_DEATHFISH, “[^a-z A-Z 0-9 ()]”, “”)

Want the xaml?

1 Like

You will need to insert them in place of the ‘XXXX’s in the following expression:

System.Text.RegularExpressions.Regex.Replace(INSERTVARIABLE, “[^a-z A-Z 0-9 () XXXX XXXX XXXX]”, “”)

1 Like

Hi, could someone post the String for this regular expression? Am having difficulty getting it right because special characters and escape sequences are interpreted differently

Also, the code above permits any characters in the XXXX, instead I would like to prohibit these characters

To match those characters we shall use the expression


The backslash is a metacharacter so we need to escape it with another backslash.