删除字符串中的点和空格

问题描述

我想用正则表达式.删除 和空格text.replace(/[ .]+/g,'')

这是8串12.34.5678;这是另外13串1234 5678 9123 0好吗?

但是主要的问题是它会删除句子中的所有点和空格。

thisisan8-string12345678; thisisanother13-string1234567891230好吗?

  • 8串12.34.5678
  • 一个13串1234 5678 9123 0

需要转换为。

  • 8串12345678
  • 一个13串1234567891230

所以句子将是:

这是8串12345678;这是另外13串1234567891230好吗?

我在做什么错?我一直坚持寻找/匹配正确的解决方案。

解决方法

您可以使用

s.replace(/(\d)[\s.]+(?=\d)/g,'$1')
s.replace(/(?<=\d)[\s.]+(?=\d)/g,'')

请参见regex demo

详细信息

  • (\d)-组1(替换模式中的$1是组的值):一个数字
  • [\s.]+-一个或多个空格或.个字符
  • (?=\d)-确定正向,确保下一个字符为数字。

请参阅JavaScript演示

const text = 'This is an 8-string 12.34.5678; and this is another 13-string 1234 5678 9123 0 okay?';
console.log(text.replace(/(\d)[\s.]+(?=\d)/g,'$1'));