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 8834303
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T08:58:54+00:00 2026-06-14T08:58:54+00:00

Is there any way of using RegEx.Matches to find, and write back matched values

  • 0

Is there any way of using RegEx.Matches to find, and write back matched values but in different (alphabetical) order?

For now I have something like:

var pattern = @"(KEY `[\w]+?` \(`.*`*\))";
var keys = Regex.Matches(line, pattern);

Console.WriteLine("\n\n");
foreach (Match match in keys)
{
    Console.WriteLine(match.Index + " = " + match.Value.Replace("\n", "").Trim());
}

But what I really need is to take table.sql dump and sort existing INDEXES alphabetically, example code:

line = "...PRIMARY KEY (`communication_auto`),\n  KEY `idx_current` (`current`),\n  KEY `idx_communication` (`communication_id`,`current`),\n  KEY `idx_volunteer` (`volunteer_id`,`current`),\n  KEY `idx_template` (`template_id`,`current`)\n);"

Thanks
J


Update:
Thanks, m.buettner solution gave me basics that I could use to move on. I’m not so good at RegEx sadly, but I ended up with code that I believe can be still improved:

...
//sort INDEXES definitions alphabetically
if (line.Contains("  KEY `")) line = Regex.Replace(
    line,
    @"[ ]+(KEY `[\w]+` \([\w`,]+\),?\s*)+",
    ReplaceCallbackLinq
);

static string ReplaceCallbackLinq(Match match) 
{
    var result = String.Join(",\n  ",
        from Capture item in match.Groups[1].Captures
        orderby item.Value.Trim()
        select item.Value.Trim().Replace("),", ")")
    );
    return "  " + result + "\n";
}


Update:
There is also a case when index field is longer than 255 chars mysql trims index up to 255 and writes it like this:

KEY `idx3` (`app_property_definition_id`,`value`(255),`audit_current`),

so, in order to match this case too I had to change some code:
in ReplaceCallbackLinq:

select item.Value.Trim().Replace("`),", "`)")

and regex definition to:

@"[ ]+(KEY `[\w]+` \([\w`(\(255\)),]+\),?\s*)+",
  • 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-14T08:58:56+00:00Added an answer on June 14, 2026 at 8:58 am

    This cannot be done with regex alone. But you could use a callback function and make use of .NET’s unique capability of capturing multiple things with the same capturing group. This way you avoid using Matches and writing everything back by yourself. Instead you can use the built-in Replace function. My example below simply sorts the KEY phrases and puts them back as they were (so it does nothing but sort they phrases within the SQL statement). If you want a different output you can easily achieve that by capturing different parts of the pattern and adjusting the Join operation at the very end.

    First we need a match evaluator to pass the callback:

    MatchEvaluator evaluator = new MatchEvaluator(ReplaceCallback);
    

    Then we write a regex that matches the whole set of indices at once, capturing the index-names in a capturing group. We put this in the overload of Replace that takes an evaluator:

    output = Regex.Replace(
        input,
        @"(KEY `([\w]+)` \(`[^`]*`(?:,`[^`]*`)*\),?\s*)+",
        evaluator
    );
    

    Now in most languages this would not be useful, because due to the repetition capturing group 1 would always contain only the first or last thing that was captured (same as capturing group 2). But luckily, you are using C#, and .NET’s regex engine is just one powerful beast. So let’s have a look at the callback function and how to use the multiple captures:

    static string ReplaceCallback(Match match)
    {
        int captureCount = match.Groups[1].Captures.Count;
        string[] indexNameArray = new string[captureCount];
        string[] keyBlockArray = new string[captureCount];
        for (int i = 0; i < captureCount; i++)
        {
            keyBlockArray[i] = match.Groups[1].Captures[i].Value;
            indexNameArray[i] = match.Groups[2].Captures[i].Value;
        }
        Array.Sort(indexNameArray, keyBlockArray);
        return String.Join("\n  ", keyBlockArray);
    }
    

    match.Groups[i].Captures lets us access the multiple captures of a single group. Since these are Capture objects which do not seem really useful right now, we build two string arrays from their values. Then we use Array.Sort which sorts two arrays based on the values of one (which is considered the key). As the “key” we use the capturing of the table name. As the “value” we use the full capture of one complete KEY ..., block. This sorts the full blocks by their names. Then we can simply join together the blocks, add in the whitespace separator that was used before and return them.

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

Sidebar

Related Questions

Is there any way to extract the matched strings by using Regex in T-SQL(SQL
Sorry for this silly question, but is there any way to restrict using directives
Is there any way in C# to use a Regex, but only return (with
Is there any way using foursquare api or some other location based api to
Is there any way for using an annotation for running a function before currently
Is there any way by using JDT ASTParser, by which we can identify if
Is there any easy way using the api to get a count of all
Is there any way to validate using DataAnnotations in WPF & Entity Framework?
is there any way to avoid using tmp table? I am using a query
is there any way to avoid using tmp table? I am using a query

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.