Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - Replace all dots,special characters except for the file extension

Tags:

c#

regex

I want a regex in such a way that to replace the filename which contains special characters and dots(.) etc. with underscore(_) except the extension of the filename.

Help me with an regex

like image 583
venkat Avatar asked Dec 29 '22 05:12

venkat


2 Answers

try this:

([!@#$%^&*()]|(?:[.](?![a-z0-9]+$)))

with the insensitive flag "i". Replace with '_'

The first lot of characters can be customised, or maybe use \W (any non-word)

so this reads as:

replace with '_' where I match and of this set, or a period that is not followed by some characters or numbers and the end of line

Sample c# code:

var newstr = new Regex("([!@#$%^&*()]|(?:[.](?![a-z0-9]+$)))", RegexOptions.IgnoreCase)
    .Replace(myPath, "_");
like image 94
Luke Schafer Avatar answered Dec 31 '22 19:12

Luke Schafer


Since you only care about the extension, forget about the rest of the filename. Write a regex to scrape off the extension, discarding the original filename, and then glue that extension onto the new filename.

This regular expression will match the extension, including the dot.: \.[^.]*$

like image 43
Wayne Conrad Avatar answered Dec 31 '22 18:12

Wayne Conrad