I am trying to get the following Regex expressions into a single line.
filename = Regex.Replace(filename, @"[^a-z0-9\s-!/\-_\.\*\(\)']", ""); // Remove all non valid chars
filename = Regex.Replace(filename, @"\s+", " ").Trim(); // convert multiple spaces into one space
filename = Regex.Replace(filename, @"\s", "_"); // //Replace spaces by dashes
>Solution :
You can use
filename = Regex.Replace(filename, @"[^a-z0-9\s!/_.*()'-]|^\s+|\s+$|(\s+)", m => m.Groups[1].Success ? "_" : "");
The regex matches
[^a-z0-9\s!/_.*()'-]|– any char but lowercase ASCII letters, digits, whitespace,!,/,_,.,*,(,),'and-, or^\s+|– start of string and then one or more whitespaces, or\s+$|– one or more whitespaces and then end of string(\s+)– Group 1: one or more whitespaces in any other context.
If Group 1 matches, the replacement is a _ char, else, the replacement is an empty string (the match is removed).
See the regex demo.