I have a regular expression which uses GroupCollection
s 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 GroupCollection
s 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).