In a c# program, I want to write file, in a folder where other file may exists. If so, a suffix may be added to the file myfile.docx
, myfile (1).docx
, myfile (2).docx
and so on.
I'm struggling at analysing existing file name to extract existing files' name parts.
Especially, I use this regex: (?<base>.+?)(\((?<idx>\d+)\)?)?(?<ext>(\.[\w\.]+))
.
This regex outputs:
╔═══════════════════════╦══════════════╦═════╦═══════════╦═══════════════════════════════════╗
║ Source Filename ║ base ║ idx ║ extension ║ Success ║
╠═══════════════════════╬══════════════╬═════╬═══════════╬═══════════════════════════════════╣
║ somefile.docx ║ somefile ║ ║ .docx ║ Yes ║
║ somefile ║ ║ ║ ║ No, base should be "somefile" ║
║ somefile (6) ║ ║ ║ ║ No, base should be "somefile (6)" ║
║ somefile (1).docx ║ somefile ║ 1 ║ .docx ║ Yes ║
║ somefile (2)(1).docx ║ somefile (2) ║ 1 ║ .docx ║ Yes ║
║ somefile (4).htm.tmpl ║ somefile ║ 4 ║ .htm.tmpl ║ Yes ║
╚═══════════════════════╩══════════════╩═════╩═══════════╩═══════════════════════════════════╝
As you can see, all cases are working excepted when a file name has no extension.
How to fix my regex to solve the failling cases ?
Reproduction : https://regex101.com/r/q9uQii/1
If it matterns, here the relevant C# code :
private static readonly Regex g_fileNameAnalyser = new Regex(
@"(?<base>.+?)(\((?<idx>\d+)\)?)?(?<ext>(\.[\w\.]+))",
RegexOptions.Compiled | RegexOptions.ExplicitCapture
);
...
var candidateMatch = g_fileNameAnalyser.Match(somefilename);
var candidateInfo = new
{
baseName = candidateMatch.Groups["base"].Value.Trim(),
idx = candidateMatch.Groups["idx"].Success ? int.Parse(candidateMatch.Groups["idx"].Value) : 0,
ext = candidateMatch.Groups["ext"].Value
};