Change from Regex to IF statement

patrick

Well-known member
Joined
Dec 5, 2021
Messages
305
Programming Experience
1-3
Hello

Change from Regex to IF statement

C#:
namespace Service
{
    public class Service : Iervice
    {

private readonly Func<string, bool> IsNew;
        private readonly Func<string, string> Target;
     
        public Service()
        {
            RequestTypeParser parser = new RequestTypeParser
                ((pattern) =>
                {
                    Regex regex = new Regex(pattern);
                    return (input) => regex.IsMatch(input);
                });

         
            IsNew = (string Number) => parser.Parse(Number) == RequestType.New; //<====Here(Change from Regex to IF statement)

            Target = (string requestNumber) => IsNew(Number) ? "SO" : "YS";//<====Here(Change from Regex to IF statement)

        }

        private enum RequestType
        {
            Invalid,
            Old,
            Current,
            New,
            RN
        }

        private class RequestTypeParser
        {
            public readonly Func<string, RequestType> Parse;

            public RequestTypeParser(Func<string, Func<string, bool>> regexCreator)
            {
                var IsOld = regexCreator(@"R\d{8}");
                var IsCurrent = regexCreator(@"C\d{8}");
                var IsNew = regexCreator(@"R\d{8}N");
                var IsRN = regexCreator(@"N\d{8}");

                Parse = (Number) =>
                {
                    RequestType type = RequestType.Invalid;

                    if (IsOld(requestNumber))
                        type = RequestType.Old;
                    else if (IsCurrent(requestNumber))
                        type = RequestType.Current;
                    else if (IsNew(requestNumber))
                        type = RequestType.New;
                    else if (IsRN(requestNumber))
                        type = RequestType.RN;

                    return type;
                };
            }
        }
    }
}
 
Last edited:
Looks like a gimme-the-codez...

We are not your code monkeys to do your work for you.

What problem are you running when you try to convert the regex into using if-statements?

Unless the regex is really simple in logic, typically regex's are implemented as finite state machines. If the finite state machine has looping states, then the regex cannot be converted into a simple set of if statements (unless the if statements call helper functions that facilitate looping).
 

Latest posts

Back
Top Bottom