Mayo
Mayo

Reputation: 909

regex- the longest possible value

How to set regex to search the longest possible value? For example:

Regex.Match("theValue","(the|theValue)"); // this return "the", but "theValue" is longer match, and it can match too

or

Regex.Match("the Value","(the|the Value)"); // return "the", not "the Value"
Regex.Match("the Value","[t]?[h]?[e]?"); // return "t", not longer "the"

Upvotes: 4

Views: 769

Answers (3)

w.b
w.b

Reputation: 11238

You can't get overlapping matches, your first alternating pattern the causes that the second can't match (the from input string is already taken).

If you want the longest possible match you should start with the longest pattern: "(theValue|the)".

btw Regex.Match returns only 1 match, if you want a collection that could be sorted by length you should use Regex.Matches.

Upvotes: 1

BrunoLM
BrunoLM

Reputation: 100361

Change your pattern to

\b(the|theValue)\b

or for your updated sample

\b(the Value|the)\b

In

the and also theValue

Will match "the" (first on the left) and "theValue" (at the end).

Example:

static class Program
{
    static void Main(string[] args)
    {
        var str = "the and also theValue";
        var pattern = @"\b(the|theValue)\b";

        foreach (Match match in Regex.Matches(str, pattern))
        {
            Console.WriteLine(match.Value);
        }


        Console.ReadKey();
    }
}

Outputs:

the
theValue

Upvotes: 3

Matthew
Matthew

Reputation: 25773

make theValue come first.

Regex.Match("theValue","(theValue|the)"); // returns theValue

Regex.Match("the Value","(theValue|the)"); // returns the

Upvotes: 0

Related Questions