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

  • Home
  • SEARCH
  • 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 8168809
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T20:39:04+00:00 2026-06-06T20:39:04+00:00

I have a regular expression which uses GroupCollection s in it’s capture to capture

  • 0

I have a regular expression which uses GroupCollections in it’s capture to capture a group of Item Id’s (which can be comma separated, also accounting for the final one to have the word ‘and’):

(\bItem #(?<ITEMID>\d+))|(,\s?(?<ITEMID>\d+))|(,?\sand\s(?<ITEMID>\d+))

Is there an easy way using C#’s Regex class to replace the ITEMID numbers with a url? Right now, I have the following:

foreach (Match match in matches)
{
    var group = match.Groups["ITEMID"];
    var address = String.Format(UnformattedAddress, group.Value);

    CustomReplace(ref myString, group.Value, address,
        group.Index, (group.Index + group.Length));
}

public static int CustomReplace(ref string source, string org, string replace,
    int start, int max)
{
    if (start < 0) throw new System.ArgumentOutOfRangeException("start");
    if (max <= 0) return 0;

    start = source.IndexOf(org, start);

    if (start < 0) return 0;

    var sb = new StringBuilder(source, 0, start, source.Length);

    var found = 0;
    while (max-- > 0)
    {
        var index = source.IndexOf(org, start);

        if (index < 0) break;

        sb.Append(source, start, index - start).Append(replace);
        start = index + org.Length;
        found++;
    }

    sb.Append(source, start, source.Length - start);
    source = sb.ToString();

    return found;
}

The CustomReplace method I found online as an easy way to replace one string with another inside of a string source. The problem is I’m sure that there is probably an easier way, probably using the Regex class to replace the GroupCollections as necessary. I just can’t figure out what that is. Thanks!

Example text:

Hello the items you are looking for are Item #25, 38, and 45. They total 100 dollars.

25, 38, and 45 should be replaced with the URL strings I am creating (this is an HTML string).

  • 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-06T20:39:06+00:00Added an answer on June 6, 2026 at 8:39 pm

    Your pattern works for your input, but it does have a bug. Specifically, it will match any number in your input that appears after a comma or the word ” and “.

    I went ahead and rewrote your pattern to avoid this issue. To achieve this I am actually using two regex patterns. It’s possible to pull this off using one pattern, but it’s fairly complicated and less readable than the approach I opted to share.

    The main pattern is: \bItem #\d+(?:,? \d+)*(?:,? and \d+)?
    No capturing groups are used here since I am only interested in matching the items. The (?: ... ) bit is a non-capturing group. The usage of (?:,? \d+)* is to match more than one comma separated value in the middle portion of the string.

    Once items are matched, I use Regex.Replace to format the items, then reconstruct the string to swap out the original items with the formatted items.

    Here’s an example with a couple of different inputs:

    string[] inputs =
    {
        "Hello the items you are looking for are Item #25, 38, 22, and 45. They total 100 dollars.",
        "... Item #25, 38 and 45. Other numbers 100, 20, and 30 untouched.",
        "Item #25, and 45",
        "Item #25 and 45",
        "Item #25"
    };
    
    string pattern = @"\bItem #\d+(?:,? \d+)*(?:,? and \d+)?";
    string digitPattern = @"(\d+)";
    // $1 refers to the first (and only) group in digitPattern
    string replacement = @"<a href=""http://url/$1.html"">$1</a>";
    
    foreach (var input in inputs)
    {
        Match m = Regex.Match(input, pattern);
        string formatted = Regex.Replace(m.Value, digitPattern, replacement);
        var builder = new StringBuilder(input)
                            .Remove(m.Index, m.Length)
                            .Insert(m.Index, formatted);
        Console.WriteLine(builder.ToString());
    }
    

    In case you need to use an existing method to format the URL, instead of using a regex replacement pattern, you could use the Regex.Replace overload that accepts a MatchEvaluator. This can be achieved using a lambda and is nicer than the tedious approach shown in the MSDN documentation.

    For example, let’s assume you have a FormatItem method that accepts a string and returns a formatted string:

    public string FormatItem(string item)
    {
        return String.Format("-- {0} --", item);
    }
    

    To use FormatItem you would change the Regex.Replace method used in the earlier code sample with the following:

    string formatted = Regex.Replace(m.Value, digitPattern,
                           d => FormatItem(d.Value));
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an automatically generated regular expression, which basically is one big or group
I have a python function which uses a regular expression to match one (the
I have a regular expression in which I'm trying to extract every group of
I have string like Rupeshposts-this-question I need a regular expression which can check whether
I have a little application which uses regular expressions under VB6. It works perfectly
I have a regular expression which accept time in a specific format like the
I have the following regular expression which is used to give me the tags
I have a regular expression ^[a-zA-Z+#-.0-9]{1,5}$ which validates that the word contains alpha-numeric characters
I have written regular expression which converts text links into clickable link. The code
I have the following Regular Expression which matches an email address format: ^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$ This

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.