chardex
chardex

Reputation: 11

Empty replacement result, when regex doesnt match

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).

Upvotes: 1

Views: 141

Answers (2)

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

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.

Upvotes: 1

Pbirkoff
Pbirkoff

Reputation: 4702

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

Upvotes: 0

Related Questions