tags:

views:

29

answers:

2
Regex.Replace("some big text", "^.+(big).+$", "$1"); // "big"
Regex.Replace("some small text", "^.+(big).+$", "$1"); // "some small text", but i need here empty string

I need to select a value from the string. It's ok, when the string matches the pattern. But when the string doesn't match, there is an original string in replacement result. I need an empty string, when string doesn't match pattern (only using replacement).

A: 

Use the Regex.Match Method. This way you can first check if the value matches. If so, you can do the replace. Otherwise, you just return a String.Empty.

More on Regex.Match can be found at: http://msdn.microsoft.com/en-us/library/twcw2f1c.aspx

Pbirkoff
I know this, but i can't use Regex.Match method. I can use only replace.I'm using Yahoo Pipes, and there is only replce function for selecting values. I can't add match method before.
chardex
+1  A: 

Although the correct way would be to use a match function, you could fake it by allowing it to match arbitrary strings if your original match fails:

Regex.Replace("some big text", "^.+(big).+$|^(.*)$", "$1$2"); // "big"
Regex.Replace("some small text", "^.+(big).+$|^(.*)$", "$1$2");

It will not attempt to match the catch-all regex unless the first part fails if written out in that order.

Max Shawabkeh