如何在字符串中屏蔽潜在手机号码?解决Google Cloud DLP非国际格式号码识别问题
解决方案
以下两种方案可适配非国际标准格式的手机号屏蔽需求:
方案1:扩展Cloud DLP自定义检测规则(推荐)
默认Cloud DLP手机号检测器仅适配带国际区号、分隔符的标准化号码,你可以新增自定义信息类型匹配对应手机号规则,直接复用DLP的屏蔽能力,无需额外开发字符串遍历逻辑:
- 新增自定义信息类型的正则规则为
1[3-9]\d{9},可覆盖绝大多数中国大陆民用手机号段,如有其他国家/地区的手机号检测需求可自行扩展对应正则 - 可同时保留默认的
PHONE_NUMBER检测规则,同时覆盖国际标准格式和自定义格式的手机号 - 支持灵活配置屏蔽规则,比如全量替换为
***、部分掩码等
Node.js 示例代码:
const { DlpServiceClient } = require('@google-cloud/dlp'); const dlp = new DlpServiceClient(); async function deidentifyPhoneNumber(text) { const projectId = await dlp.getProjectId(); // 自定义手机号检测规则 const customInfoTypes = [ { infoType: { name: 'CN_MOBILE_PHONE' }, regex: { pattern: '1[3-9]\\d{9}' }, likelihood: 'LIKELY' } ]; // 屏蔽配置:示例为保留手机号前3位、后4位,中间替换为**** const deidentifyConfig = { infoTypeTransformations: { transformations: [ { infoTypes: [{ name: 'CN_MOBILE_PHONE' }, { name: 'PHONE_NUMBER' }], primitiveTransformation: { replaceConfig: { newValue: { stringValue: '****' }, // 如需全量替换可删除surrogateConfig配置 surrogateConfig: { priorSurrogateCount: 3, subsequentSurrogateCount: 4 } } } } ] } }; const request = { parent: `projects/${projectId}/locations/global`, deidentifyConfig: deidentifyConfig, inspectConfig: { customInfoTypes: customInfoTypes }, item: { value: text } }; const [response] = await dlp.deidentifyContent(request); return response.item.value; } // 测试调用 deidentifyPhoneNumber('Do transaction over phone to bypass fee. My number: 18776967786') .then(res => console.log(res));
方案2:本地预匹配处理(轻量场景适用)
如果仅需要手机号屏蔽能力、不需要DLP的其他敏感数据检测能力,可直接在本地通过正则遍历匹配手机号后做屏蔽,性能开销更低:
function maskPhoneNumber(text) { // 手机号匹配正则,可根据需要扩展其他国家/地区的手机号规则 // 如需避免长数字串误匹配,可调整为带单词边界的版本:/\b1[3-9]\d{9}\b/g const phoneReg = /1[3-9]\d{9}/g; return text.replace(phoneReg, match => { // 示例:保留前3位后4位,中间替换为**** return `${match.slice(0,3)}****${match.slice(-4)}`; }); } // 测试 console.log(maskPhoneNumber('Do transaction over phone to bypass fee. My number: 18776967786')); // 输出:Do transaction over phone to bypass fee. My number: 187****7786
内容的提问来源于stack exchange,提问作者FlutterFirebase
相关产品推荐
相关产品推荐

