In C# regex, how do I optimise matching a sub-sequence of characters

The most suitable to have is what @eocron mentioned above:

"true".StartsWith(inputString) || "false".StartsWith(inputString)

If you are searching for regex-based approach:

string pattern = @"^t(r(u(e)?)?)?$";
string input = "trueString";

Another custom solution tailor-made for this to have a custom implementation like below :

static bool StartsWithSequence(string input, string sequence)
    {
        if (input.Length < sequence.Length)
        {
            return false;
        }

        for (int i = 0; i < sequence.Length; i++)
        {
            if (input[i] != sequence[i])
            {
                return false;
            }
        }

        return true;
    }

And consume it like below :

    string input = "truestring";

        if (StartsWithSequence(input, "t"))
        {
            Console.WriteLine("Match!");
        }
        else
        {
            Console.WriteLine("No match.");
        }

The above approach compares the first characters of the input string with the characters in the specified sequence. If they match, it will return true if not it will return false. In this way, you can extend this method to handle longer sequences as needed.

Read more here: Source link