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?

+3


source to share


2 answers


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, "[0-9]", "0");
}

      

And then use it with this code:



string input = "9999999099999Thompson534543";
MatchEvaluator evaluator = new MatchEvaluator(Program.Evaluate);
string replaced = Regex.Replace(input, "(?:^|[^0-9])[0-9]{2,8}(?:$|[^0-9])", evaluator);

      

Regular expression:

  • (?:^|[^0-9])

    - must start or start with a non-digit
  • [0-9]{2,8}

    - capture 2 to 8 digits
  • (?:$|[^0-9])

    - must be at the end or after it not contain numbers
+2


source


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

      

0


source







All Articles