dart正则替换手机号中间四位为*

2,642 阅读1分钟

js代码示例:

let str = '13888888888';
let reg = /(?<=\d{3})(\d{4})/;
str.replace(reg,"****"); //138****8888

dart的一种写法

String phoneNumber = '13888888888';
String phoneNumberStr = phoneNumber.replaceFirst(new RegExp(r'\d{4}'), '****', 3);

replaceFirst用法:

String replaceFirst(Pattern from, String to, [int startIndex = 0])
dart:core

Returns a new string in which the first occurrence of [from] in this string is replaced with [to], starting from [startIndex]:

'0.0001'.replaceFirst(new RegExp(r'0'), ''); // '.0001'
'0.0001'.replaceFirst(new RegExp(r'0'), '7', 1); // '0.7001'