Thursday, March 22, 2007

Regex: Using named groups in .NET Regular Expressions

When you match a group in a regular expression, you can reference them in the replace expression with the syntax "$1, $2". But, the better way is to give every group a name.

in search -> (?....pattern...)
in replace -> ${name}
\k --> back reference to a named match

Example:
SearchPattern = (?<tag>bold)>(?<text>[\s\S]+?)</\k<tag>>
ChangePattern =
<${tag}><font color=red>${text}</font></${tag}>


Text:
<bold>this text will be red</bold>

Result:
<bold><font color=red>this text will be red</font></bold>

I hope everything is clear in the example :)

No comments: