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
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, "_");
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.: \.[^.]*$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With