1

I am converting some code from Perl into .NET. I have this s/// pattern replacement:

$text =~ s/<A HREF="([^"]+)">\Q\1\E</A>"/$1/gi;

I use the Perl \Q and \E to escape the text I am matching in the first capture, the URL portion of an HREF attribute.

How do I do the same thing in .NET? I've read about using Regex.Escape() to escape text for a regular expression, but how can I use it WITHIN the regular expression that is performing the match? (Or do I even need to do that?)

So right now I'm not doing anything special, and wondering if this will continue to work as well as my Perl regex has been:

text = Regex.Replace(text, @"<A HREF=""([^""]+)"">\1</A>", "$1", RegexOptions.IgnoreCase);
4

1 に答える 1

2

Perl では \Q...\E は必要ありません。実際、Perl が機能しなくなります。これは、'\1' が最初の一致の内容に置き換えられるのではなく、文字どおりに取られることを意味するためです。

\Q...\E は、正規表現で特殊な文字を引用するためのものです。後方参照で置き換えられた文字列は、正規表現構文として再評価されず、文字どおりに既に取得されています。

置換文字列に挿入されたものについても同じことが言えます。\Q...\E または Regex.Escape() が必要なのは、正規表現に補間したいテキストを含む regex-land の外部からの変数があり、その一部を誤って正規表現として扱わない場合のみです。式のメタ文字。

于 2012-04-26T01:08:27.690 に答える