Replace digits of length 2 to 8 with a specific character using regex
We have a security issue where a certain field in the database contains some sensitive information. I need a way to find numbers from 2 to 8, replace the digits with "filler" of the same length.
For example:
Jim8888Dandy
Mike9999999999Thompson * Note: this is 10 in length and we don't want to replace the digits
123Area Code
Tim Johnson5555555
In these cases, at any time we find a number that is between 2 and 8 (inclusive), then I want to replace / fill / replace this value with 0 and keep the length of the original digits
Final result
Jim0000Dandy
Mike9999999999Thompson
000Area Code
Tim Johnson0000000
Is there an easy way to accomplish this with RegEx?
source to share
You need to provide a static evaluator method to replace. It replaces the numbers in the match with zeros:
public static string Evaluate(Match m)
{
return Regex.Replace(m.Value, "[09]", "0");
}
And then use it with this code:
string input = "9999999099999Thompson534543";
MatchEvaluator evaluator = new MatchEvaluator(Program.Evaluate);
string replaced = Regex.Replace(input, "(?:^[^09])[09]{2,8}(?:$[^09])", evaluator);
Regular expression:

(?:^[^09])
 must start or start with a nondigit 
[09]{2,8}
 capture 2 to 8 digits 
(?:$[^09])
 must be at the end or after it not contain numbers
source to share
For the clever regex department only. This is not an efficient regular expression.
(?<=(?>(?'front'\d){0,7}))\d(?=(?'back'(?'front'\d)){0,7}(?!\d))((?'front')(?'back'))
Replace with 0
.
/(?<=(?>(?'front'\d){0,7})) # Measure how many digits we're behind.
\d # This digit is matched
(?=
(?'back' # Measure how many digits we're in front of.
(?'front'\d)){0,7}
# For every digit here, subtract one group from 'front',
# As to assert we'll never go over the < 8 digit requirement.
(?!\d) # no more digits
)
(
(?'front') # At least one capturing group left for 'front' or 'back'
(?'back') # for > 2 digits requirement.
)/x
source to share