Regex - Replace all dots, special characters except file extension

I want a regular expression so that it replaces a file name that contains special characters and periods (.), Etc. with an underscore (_), except for the file name extension.

Help me with regex

+3
source share
4 answers

try the following:

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

with insensitive flag "i". Replace '_'

The first batch of characters can be customized or maybe use \ W (any non-word)

so it looks like:

replace with "_", where I match, and this set, or the period that some characters or numbers do not follow, and the end of the line

C # code example:

var newstr = new Regex("([!@#$%^&*()]|(?:[.](?![a-z0-9]+$)))", RegexOptions.IgnoreCase)
    .Replace(myPath, "_");
+6
source

, . , , , .

, .: \.[^.]*$

+2

, ? - ( ):

static readonly Regex removeChars = new Regex("[-. ]", RegexOptions.Compiled);
static void Main() {
    string path = "ab c.-def.ghi";
    string ext = Path.GetExtension(path);
    path = Path.ChangeExtension(
        removeChars.Replace(Path.ChangeExtension(path, null), "_"), ext);
}
+1

, this, ?

+1

Source: https://habr.com/ru/post/1729018/


All Articles