Match groups and subgroups in a string

i have a dynamic string, for example "([1] * [5]) / 100"

what I want to do is find all the matches of strings hed within the square brackets. for each instance i want to tun some logic and do a replace. e.g. in the above example [1] i would be replacing with [Joe Bloggs] after doing a lookup on the id.

is possible with regex matches somehow?

(Moderator: Thread moved to the Regular Expression Forum and Title tweaked for quicker thread understanding during a search)
[550 byte] By [WeeBubba] at [2008-2-15]
# 1

Hi,

if you used curly brackets, you could use the string.Format method:

string text = "({0} * {1}) / 100";
string result = string.Format(text, "Joe Bloggs", "Mary Bloggs");

Would that work for you?

If not, here's the regex expression:

MatchCollection matches = Regex.Matches(text, "(?<=\\[)\\d(?=\\])");

Andrej

AndrejTozon at 2007-8-30 > top of Msdn Tech,.NET Development,Regular Expressions...
# 2

thanks a lot. is it also possible using Regex to provide a match collection where each match is split into 2 groups?

example string: "[Category1\Subject4] * [Category2\Subject7] / 100"

where i want to loop through each items in the square backets but have them also split by the "\" character.

i.e. match1.group1 = "Category1"

match2.group2 = "Subject4"

match2.group1 = "Category2"

match2.group2 = "Subject7"

thanks

WeeBubba at 2007-8-30 > top of Msdn Tech,.NET Development,Regular Expressions...
# 3

Of course:

string text = "[Category1\\Subject4] * [Category2\\Subject7] / 100";
MatchCollection matches = Regex.Matches(text, "(?<=\\[)(?<category>.*?)\\\\(?<subject>.*?)(?=\\])");
foreach (Match match in matches)
{
MessageBox.Show(string.Format("Category: {0}, Subject: {1}", match.Groups["category"], match.Groups["subject"]));
}

Andrej

AndrejTozon at 2007-8-30 > top of Msdn Tech,.NET Development,Regular Expressions...
# 4
Hi Wee Bubba,

Did the posts resolve the problem?

If so mark the

post(s) that helped you as the answer(s), so when others search the

new Regex forum, they might be more inclined to look at a successful post than a

non successful one...in the

search results the Answered posts are bubbled to the top before the

unanswered.

Or post why it failed for

you. Thanks.

OmegaMan at 2007-8-30 > top of Msdn Tech,.NET Development,Regular Expressions...

.NET Development

Site Classified