Matching a part with Regex in C#

Viewed 59

How to read @"TC__(\d{4}|\d{3})_8exp", if it is in the end of the Line!

I am getting two results:

TC__4373_8exp
TC__4373_8exp_source

I want just:

TC__4373_8exp

Code:

Regex reg = new Regex(@"TC__(\d{4}|\d{3})_8exp");
var FileNames_List_Jetzt_Dateien = Directory.GetFiles(yourPath, "*.html").Where(path => reg.IsMatch(path)).Select(Folder_Jetzt_Dateien => Path.GetFileNameWithoutExtension(Folder_Jetzt_Dateien));
1 Answers

You can use TC__\d{3,4}_8exp$ regex and you need to make sure the regex checks just the file name without extension:

var reg = new Regex(@"TC__\d{3,4}_8exp$"); 
var FileNames_List_Jetzt_Dateien = Directory.GetFiles(yourPath, "*.html")
    .Where(path => reg.IsMatch(Path.GetFileNameWithoutExtension(path)))
    .Select(Folder_Jetzt_Dateien => 
        Path.GetFileNameWithoutExtension(Folder_Jetzt_Dateien)); 

The TC__\d{3,4}_8exp$ regex matches TC__, three or four digits, _8exp at the end of string.

The .Where(path => reg.IsMatch(Path.GetFileNameWithoutExtension(path))) part will make sure your regex checks the file name without extension (i.e. without the .html part).

See the regex demo.

You can simplify the code further to only call Path.GetFileNameWithoutExtension() once by selecting all file names with extension before running the regex check:

var reg = new Regex(@"TC__\d{3,4}_8exp$"); 
var FileNames_List_Jetzt_Dateien = Directory.GetFiles(yourPath, "*.html")
    .Select(Folder_Jetzt_Dateien => 
        Path.GetFileNameWithoutExtension(Folder_Jetzt_Dateien))
    .Where(path => reg.IsMatch(path));
Related