Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex substitution: what is the difference between $& and Value (in lambda expression)?

Tags:

c#

regex

Say I want to use a regular expression to add "test" before each word in a string.

string MyText="hello world"
string Pattern = "\w+";

I could do this:

Regex.Replace(MyText, Pattern, "test$&")

or this:

Regex.Replace(MyText, Pattern, m=>"test"+m.Value)

I would get the same result so what's the difference between $& and Value in the lambda expression? If there's not difference in terms of results, is there a performance issue?

like image 332
Anthony Avatar asked Aug 14 '13 14:08

Anthony


1 Answers

Lambdas are anonymous methods which work just the same as regular ones. The one declared in your example is equivalent to: string Convert(RegexMatch match) { return "test" + match.Value; }. Using this syntax can give you access to a much richer range of possibilities then using the Regex expression used in your first example.

like image 91
Zache Avatar answered Oct 24 '22 02:10

Zache