Link to home
Start Free TrialLog in
Avatar of trevor1940
trevor1940

asked on

C#: Regex replace with multiple options

Hi
in the code bellow I'm trying to remove 1080p | HD either in or out of ()
I butl the using regexq101
this appears to work except for last witespace
however I'm not getting the expacted reults


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;

namespace Remove1080p
{
    class Program
    {
        static void Main(string[] args)
        {
            string Root = "";
            Console.WriteLine(@"Drag folder");
            string Ans = Console.ReadLine();
            if (Ans == "")
            {
                Console.WriteLine("Need a folder");

                Console.WriteLine(@"Drag folder");
                Ans = Console.ReadLine();
            }
            if (Ans != "")
            {
                Root = Ans;
                if (Root.EndsWith(@""""))
                {
                    Root = Root.Trim(new char[] { '"' });
                    Console.WriteLine("trimed " + Root);
                }
            }
            Regex regex = new Regex(@"(\s+(\(1080p\s+HD\))|(\(1080p\)|(\(regex\))|1080p|720p|HD)\s+)");

            string[] Files = Directory.GetFiles(Root);
            foreach (string file in Files)
            {
                Console.WriteLine("File " + file);
                FileInfo fi = new FileInfo(file);
                string Ext = fi.Extension;

                string FN = Path.GetFileNameWithoutExtension(fi.Name);
                Match hdMatch = regex.Match(FN);
                if (hdMatch.Success)
                {
                   string NewFN = regex.Replace(FN,"");
                    NewFN.Trim();
                    NewFN.TrimEnd();
                    NewFN = Root + "\\" + NewFN + Ext;
                    if (!File.Exists(NewFN))
                    {
                        Console.WriteLine("NewFile = {0}", NewFN);

                    File.Move(file, NewFN);
                    }
                }

            }
            Console.ReadLine();
        }
    }
}

Open in new window


Test Strings used on regex101

Input => C# output
Adult World (1080p HD)  => Adult World | note space
After Earth 1080p HD  => After Earth HD
Ghost Rider (HD)  => NO Match
After Earth 1080p  => NO Match
Rango HD   => NO Match

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of louisfr
louisfr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of trevor1940
trevor1940

ASKER

Thanx that worked