By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 769 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

Using Regex to capture phrases inside of tags

P: n/a
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.
Aug 9 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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
Aug 9 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.