我想使用正则表达式 text.replace(/[ .]+/g, '')
删除点 .
和空格
。
This is an 8-string
12.34.5678
; and this is another 13-string1234 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-string1234567891230
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/