Using Regex to capture phrases inside of tags

G

Guest

I have a regular expression for capturing all occurrences of words contained
between {{ and }} in a file. My problem is I need to capture what is between
those symbols. For instance, if I have tags such as {{FirstName}},
{{LastName}}, and {{Address}} placed in the file, I need to be able to
capture the text strings of FirstName, LastName and Address, respectively.
I'm sure it can be done with Regex as easily as finding the locations of all
such tagged items within the file, but I can't figure it out. Any help would
be greatly appreciated.
 
J

Jesse Houwing

Hello AlBruAn,
I have a regular expression for capturing all occurrences of words
contained between {{ and }} in a file. My problem is I need to
capture what is between those symbols. For instance, if I have tags
such as {{FirstName}}, {{LastName}}, and {{Address}} placed in the
file, I need to be able to capture the text strings of FirstName,
LastName and Address, respectively. I'm sure it can be done with
Regex as easily as finding the locations of all such tagged items
within the file, but I can't figure it out. Any help would be greatly
appreciated.

Basically you have two options:
1) use a capturing group to capture the contents of the {{}}
2) use look arounds to ensure the {{ and }} are directly surrounding your
search string

If you need to replace the whole contents of the {{..}} including the {},
the first solution is the easiest

Solution 1
===================================

Regex rx = new Regex("{{(?<value>\w+)}}");
Match m = rx.Match(input);
while (m != null)
{
string contents = m.Groups["value"].Value;
m = m.NextMatch();
}


The contents of the named group value (?<value>...) will be stored in the
Match.Groups collection.

Solution 2
===================================

Regex rx = new Regex("(?<={{)<value>\w+(?=}})");
Match m = rx.Match(input);
while (m != null)
{
string contents = m.Value;
m = m.NextMatch();
}

The regex engine will make sure that the string between (?<=..) will be in
front of the text being catured. The same system is used to ensure the text
between (?=..) is following the text being captured.

If you need to replace these template fields so to speak, you should have
a look at MatchEvaluators. I'd also be happy to explain them.

Kind regards,

Jesse Houwing
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top