C#
C# 정규식을 활용한 계좌번호 ,휴대폰 번호 마스킹 처리.
헝그리코더
2021. 9. 8. 11:25
경우에 따라 (계좌번호,휴대폰) 부분 마스킹 처리가 필요하여 정규식 패턴 몇 가지 정리 하려고 한다. (업데이트 중..)
Regex Test https://regex101.com/
regex101: build, test, and debug regex
Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java. Features a regex quiz & library.
regex101.com
samplecode
using System;
using System.Text.RegularExpressions;
public class Program
{
static void Main(string[] args)
{
string[] input = new[] {
"123-00-0012-349",
"1234-1234-1234-1234",
"010-8888-9999"
};
string[] pattern = new[] {
// 1234-1234-1234-1234 패턴
@"((?<=\d{4}[ -]\d{4}[ -]\d{2})\d{2})|(?<=\d{4}[ -]\d{4}[ -]\d{4}[ -])\d{4}",
// 123-00-0012-349 패턴
@"((?<=\d{3}[ -]\d{2}[ -]\d{2})\d{2})|((?<=\d{3}[ -]\d{2}[ -]\d{4}[ -])\d{2})",
// 010-8888-9999 패턴
@"\d{4}(?!\d{0,4}$)"
};
string replacement = string.Empty;
for (int i = 0; input.Length > i; i++)
{
for (int k = 0; pattern.Length > k; k++)
{
if (Regex.IsMatch(input[i], pattern[k]) == true)
{
replacement = Regex.Replace(input[i], pattern[k], new MatchEvaluator(math => new string('*', math.Length)));
Console.WriteLine(replacement);
break;
}
}
}
}
}
output
123-00-00**-**9
1234-1234-12**-****
010-****-9999