RegEx for encoding substitutions with index of match?

0 views
Skip to first unread message

l_d_allan

unread,
Mar 20, 2006, 12:23:24 PM3/20/06
to Regex
<alert comment="regex and perl newbie">

I'm a C++ programmer using a regex library to do some conversions of
html.

I've got input such as:
<p>The chair could be red or blue. It might be green.</p>

I want to convert lines like the above to set up links so the line
above becomes something like:
<p>The chair could be <a=0>red</a> or <a=1>blue</a>. It might be
<a=2>green</a>.</p>

I could write three separate statements, such as:
Find: red
Substitute: <a=0>red</a>

Find: blue
Substitute: <a=1>blue</a>

Find: green
Substitute: <a=2>green</a>

Can this be done in one statement, so that the index of the matched
alternative can be used as a variable:
Find: (red|blue|green)
Substitute: <a=#>$1</a>

In other words, can the regular expression library (such as pcre or
greta or boost::regex) detect which of the alternatives was actually
matched?

</alert>

Sergei Z

unread,
Mar 21, 2006, 11:23:13 AM3/21/06
to Regex
in .NET Regex Class such substitutions are easily handled by using
MatchEvaluator delegate. Regex object matches say 'red' , then passes
the match to MatchEvaluator's function which carries out corresponding
string processing of

red

into

<a=0>red</a> [using case structure e.g. to
distunguish between red blue green]

and then passes it back to the Regex object, which does the replace.
Hope smth similar is avail in pcre.

Reply all
Reply to author
Forward
0 new messages