Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine multiple regex expressions into a single line

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading