Am I understanding how RegEx.Replace works in C#/.NET? I want this:
Test: String
To become this:
Test String
var cleanString = Regex.Replace("Test: String", @"^[\w\*\$][\w\s\-\$]*(\(\d{1,}\)){0,1}$", "");
Yet it cleanString evaluates to:
Test: String
What am I doing wrong?
EDIT: I’m getting a regex validation string from a third party source, so I can either use that regex validation string or somehow figure out the valid characters in the regex validation string, and loop through an invalid character array. This is why I chose to do regex, which I never usually use.
Regex.Replacewon’t do what you’re trying to do. The regex pattern used inRegex.Replaceneeds to match on the bits of the string that you want to replace.The string validation pattern you’re trying to use matches only a valid string. You can use
Regex.IsMatchwith this pattern to check whether or not a string is valid, but it won’t, and can’t, show you which characters in the string prevent the match from succeeding.You need to use a pattern that matches bad characters. A first stab for this situation would be
[^\w\*\-\d\(\)\s\$]+. This will match any character not allowed by the validation string, but is still not good enough. For example, it won’t match non-digit characters between the optional parentheses, and it won’t enforce a single pair of matching parentheses. When you start to consider all the possible ways a string could be invalid as single Regex pattern to strip out invalid characters will quickly become unworkable.