我有一批像这样的字符串
32-1233-21323300
32-dsdw-ee322300
32-ee23-cd3de300
更换后的预期结果
3451-1233-213.233
3451-dsdw-ee3.223
3451-ee23-cd3.de3
......
我想要的是在函数中使用正则表达式来传输数据格式。
function dataTransfer('32 -xxxx-xxxxxx00','4351-xxxx-xxx.xxx')
我以前的代码是这样的:
arrData(d=>{
d = d.replace(/^[32]/,"3451").replace(/[00]$/,"");
d = d.slice(0, 13) + '.' + d.slice(13);
})
但我认为应该有其他好的解决方案。有什么建议吗?
附录:感谢您的所有反馈。放弃,我想要的是尝试分析像'32 -xxxx-xxxxxx00'这样的格式。 x代表任何字符。
用户可以输入像32-xxxx-xxxxxx00和4351-xx0x-xxx.xx9这样的参数。我将获得源和目标格式。然后我尝试分析格式并使用RegEx来完成数据传输。但这似乎太复杂了。
可能是这个正则表达式帮助你。试试下面的正则表达式
“32-1233-21323300”.replace(/ ^(32)/,“3451”)。替换(/([0] +)$ /,“”)。 ] {3})$ /,“。$ 1”)
输出:3451-1233-213.233作为您的期望。
我不明白为什么你的解决方案很糟糕,但如果你想要1个正则表达式,你可以使用this:
^(?:32)(-[\da-z]{4}-[\da-z]{3})([\da-z]{3})
它将产生2组然后你可以做"3451"+group1+"."+group2
来创建你的最终字符串
你可以使用/(^32)(.{9})(.{3})(00$)/
,合并子串:
const a = '32-dsdw-ee322300'.replace(/(^32)(.{9})(.{3})(00$)/, `3451$2.$3`)
console.log(a)
你只需要这两个替换。检查这个JS演示。
var arr = ['32-1233-21323300','32-dsdw-ee322300','32-ee23-cd3de300']
for (s of arr) {
console.log(s + " --> " + s.replace(/^32/,'3451').replace(/(.{3})(.{3})00$/,'$1.$2'));
}
你可以很容易地做到这一点没有正则表达式:
var s = "32-1233-21323300";
if(s.startsWith("32-") && s.endsWith("00")){
// remove 32- at the beginning
s = "3451-" + s.slice(3);
// remove 00 at the end
s = s.slice(0, s.length - 2);
// insert dot
s = s.slice(0, s.length - 3) + "." + s.slice(s.length - 3);
console.log(s);
}