Pedro77
Pedro77

Reputation: 5294

Find number pattern in string and remove it

I need to remove a pattern from a string, I think regex could do the job, but I'm having trouble solving this.

The pattern must be in the end of the string.

string fileName = "File (123)";
string pattern = " (0)";
string cleanName = PatternRemover(fileName, pattern);
//Should result in: cleanName == "File"

Edit: Ok, here is the code that I'm using now after your answers:

    public static string GetNextFilePath2(string fullPath, ref uint id, string idFormat)
    {
        string dir = Path.GetDirectoryName(fullPath);
        string ext = Path.GetExtension(fullPath);
        string fileNameNoExt = Path.GetFileNameWithoutExtension(fullPath);
        if (ext.Length > 0 && ext[0] != '.')
            ext = "." + ext;

        string baseName = Regex.Replace(fileNameNoExt, @"\s\(\d+\)", "");

        string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
        string path = Path.Combine(dir, fileName);
        while (File.Exists(path))
        {
            id++;
            fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
            path = Path.Combine(dir, fileName);
        }
        return path;
    }

It works, but:

  1. It always start to count from id, I think it may be better to start from the file name number.
  2. I was hopping to use something like "(0)" as a method parameter that would indicate the pattern to be removed and also the "(" would be parametrized. I'm doing it "manually" now on this line: string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;

Upvotes: 0

Views: 137

Answers (3)

Matt Burland
Matt Burland

Reputation: 45155

You could use:

\s\(\d+\)\.jpg

assuming you do actually want the extension removed and the extension is always ".jpg". Otherwise:

\s\(\d+\)

Looks for a set of digits in brackets proceeded by a space.

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

Using regex:

var subject = "File (123).jpg";
var fileNameWithExtension = Regex.Replace(subject,@"\s*\(\d+\)","");
var fileNameWithoutPath = Path.GetFileNameWithoutExtension(fileNameWithExtension);

And thanks for @habib, I'd not have come with Path.GetFileNameWithoutExtension in this for stripping the extension.

Upvotes: 3

Habib
Habib

Reputation: 223392

You can do that without REGEX like:

string newFileName = new String(fileName
                               .Where(r => !char.IsDigit(r)
                                           && r != '('
                                           && r != ')'
                                           && r != ' ').ToArray());

This would give you File.jpg

If you only want to get the file name then you can use:

string fileNameWithoutPath = Path.GetFileNameWithoutExtension(newFileName);
// it would give you `File`

Upvotes: 6

Related Questions