I’m building a generic regular expression validator which takes in a value to compare and returns true or false on whether it is a match or not. The validator is tied to custom controls and hence the input is automatically retrieved from a property. I would like to know if .NET has syntax for string replacement within the regex. I don’t mean using the Regex.Replace method, I mean using the actual regular expression as a mechanism to replace text with something else. That way I can do:
return Regex.IsMatch(control.Text, "some regex with replacement logic built in");
More specifically I would like my regex to remove all non numeric values and then make sure it’s within a number of characters.
The ‘MatchEvaluator Delegate’ might help you here, although it is not explicitly what you requested; take a look…
Regex.Replacehas an overload that takes aMatchEvaluatordelegate, which is invoked per match. This allows you to delegate the content of the replacement string in C# code when the regular expression syntax is not expressive enough. For example:give the output “5 is less than 100”. This might be suitable here, but requires you to provide a generic replacement type.
I hope this helps.