javascript - 从字符串中删除点和空格

标签 javascript regex regexp-replace

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

This is an 8-string 12.34.5678; and this is another 13-string 1234 5678 9123 0 okay?

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

Thisisan8-string12345678;andthisisanother13-string1234567891230okay?

  • 8 字符串 12.34.5678
  • 另一个 13 字符串 1234 5678 9123 0

需要转换为。

  • 8 字符串 12345678
  • 另一个 13 字符串 1234567891230

所以句子将是:

This is an 8-string 12345678; and this is another 13-string 1234567891230 okay?

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

最佳答案

你可以使用

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'));

关于javascript - 从字符串中删除点和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64325294/

相关文章:

javascript - 可变变量可以从闭包中访问

javascript - 在不一致的字符串上拆分

正则表达式获取间隔下划线之间的字符串

regex - 如何使用 Regex 替换 Google Data Studio 中日期字段中的方括号?

python - 仅替换文件中多次出现的匹配组

javascript - 如何在不支持 CSS3 过滤器的浏览器中模糊图像

javascript - 关于预加载的建议

c++ - QRegExp 一次匹配包含 N 个单词的行,但不考虑顺序(即逻辑与)

正则表达式生成缩略图!?!?! (但这太疯狂了!)

postgresql - 使用 regexp_replace 如何用异常替换字符串