Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8917711
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T05:33:32+00:00 2026-06-15T05:33:32+00:00

Let’s say I have an arbitrary list of regexes ( IList<Regex> lst; for example).

  • 0

Let’s say I have an arbitrary list of regexes (IList<Regex> lst; for example). Is there any way to find out which one matches earlier in the string?

Of course there is the straightforward solution of trying each one on the string and seeing which match has the lowest index, but this could be inefficient on long strings.

Of course I can go back and pull the strings back out of each regex (Regex.ToString()) and concatenate them all together ("(regex1)|(regex2)|(regex3)"), but I find this to be an ugly solution, especially since it does not even indicate which regex was matched.

EDIT: Basically, is there a way to combine the already-compiled regexes without string manipulation and recompilation?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T05:33:33+00:00Added an answer on June 15, 2026 at 5:33 am

    It’s pretty well known that executing one expression with multiple groups is usually slower than executing each expression in turn. It might look like creating one expression would be faster, but actually the Regex Engine will first search the whole string to find the first expression, maybe going all the way to the end of the string, but when it finds a match it will return. So there is no way to force it to return the first Match. This is due to the way the .NET Regex engine works.

    Since each regex might start earlier in the string, but can potentially result in a longer match, you can’t limit the end of your search to the index of the currently earliest match like this:

            // WARNING WILL NOT ALWAYS RESULT IN THE RIGHT VALUES
            List<Regex> rxs = new List<Regex>(4);
            rxs.Add(new Regex("def"));
            rxs.Add(new Regex("abc"));
            rxs.Add(new Regex("bcd"));
            rxs.Add(new Regex("cde"));
    
            string target = "abcdef";
            int firstIndex = target.Length;
            string firstMatch = string.Empty;
    
            foreach (var rx in rxs)
            {
                var match = rx.Match(target, 0, firstIndex);
                if (match.Success)
                {
                    firstIndex = match.Index;
                    firstMatch = match.Value;
                    if (firstIndex == 0) break;
                }
            }
            return firstMatch;
    

    This will work when you know the maximum length each regex will match, in that case use:

            // WARNING WILL NOT ALWAYS RESULT IN THE RIGHT VALUES
            List<Regex> rxs = new List<Regex>(4);
            rxs.Add(new Regex("def"));
            rxs.Add(new Regex("abc"));
            rxs.Add(new Regex("bcd"));
            rxs.Add(new Regex("cde"));
    
            string target = "abcdef";
            int firstIndex = target.Length;
            string firstMatch = string.Empty;
    
            foreach (var rx in rxs)
            {
                var match = rx.Match(target, 0, firstIndex + GetMaxLength(rx));
                if (match.Success)
                {
                    firstIndex = match.Index;
                    firstMatch = match.Value;
                    if (firstIndex == 0) break;
                }
            }
            return firstMatch;
    

    But you can shortcircuit as soon as you find a match on the first position, saving you any potential executions after that.

            foreach (var rx in rxs)
            {
                var match = rx.Match(target);
                if (match.Success)
                {
                    if (match.Index < firstIndex)
                    {
                        firstIndex = match.Index;
                        firstMatch = match.Value;    
                    }
                    if (firstIndex == 0) break;
                }
            }
    

    With a little trickery you can use the index of your current first match candidate to limit the search, but I suspect it will actually still be slower than searching all possible matches:

            List<string> rxs = new List<string>(4);
            rxs.Add( "def");
            rxs.Add( "abc");
            rxs.Add( "bcd");
            rxs.Add( "cde");
    
            string target = "abcdef";
            int firstIndex = target.Length;
            string firstMatch = string.Empty;
    
            foreach (var rx in rxs)
            {
                var match = Regex.Match(target, @"(?<!\A[\w\W]{" + firstIndex + "})" + rx);
                if (match.Success)
                {
                    if (match.Index < firstIndex)
                    {
                        firstIndex = match.Index;
                        firstMatch = match.Value;    
                    }
                    if (firstIndex == 0) break;
                }
            }
    

    In the end, experiment and measure to find the way that works best for you.


    I do have some extra information: At least one of the Regexes will be found near the beginning of the string.

    In that case you can opt to first scan using a reasonable value for the length index, so use rx.Match(targetstring, 0, 1024 /* First scan */) and only if you don’t find a match, widen your search in a second pass. If your target string can be really large this will save a lot of compute power.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let me explain best with an example. Say you have node class that can
Let's say I have a sortable list like this: $(.song-list).sortable({ handle : '.pos_handle', axis
Let's say I have the following entity: public class Store { public List<Product> Products
Let's say you have a class library project that has any number of supplemental
Let's say I have an abstract parent class called shape, and that there are
Let me frame it this way.. Say I have an application server running on
Let's say there is a list of List<UInt32> Thus, : 12|12 23|33 33|22 11|22
Let's say you have a string (say a list of Christmas presents). presents =
Let's have an example like below: package xliiv.sandbox; import android.app.Activity; import android.os.Bundle; import android.util.Log;
Let's say I don't have photoshop, but I want to make pattern files (.pat)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.