2

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.

3
  • Are you replacing the non-numeric values with something or just removing them? Commented Mar 14, 2012 at 15:14
  • Sounds like you want a one-liner, but the problem is such that you need two lines. This doesn't seem like it would be too bad if you could first use a regex.replace to remove non-numeric characters, then run a match on an 'all numeric characters?' expression. You could probably switch your UI to use a masked text box and save a lot of trouble, though. Commented Mar 14, 2012 at 15:16
  • Just make it 2 steps. First clean up control.Text, then match it. Commented Mar 14, 2012 at 15:16

1 Answer 1

3

The 'MatchEvaluator Delegate' might help you here, although it is not explicitly what you requested; take a look...

Regex.Replace has an overload that takes a MatchEvaluator delegate, 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:

Console.WriteLine(Regex.Replace("5 is less than 10", @"\d+", 
    m => (int.Parse(m.Value) * 10).ToString()));

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.