从字符串中删除前导和尾随零

14

我有几个类似这样的字符串:

str1 = "00001011100000";  // 10111
str2 = "00011101000000";  // 11101
...
我想使用正则表达式一次性从每个字符串中去除前导和尾随的零。
到目前为止,我使用了两个不同的函数,但我想将它们结合在一起:
str.replace(/^0+/,'').replace(/0+$/,'');
2个回答

25

您可以使用一个 OR 子句 (|) 来结合两个正则表达式:

var r = '00001011100000'.replace(/^0+|0+$/g, "");
//=> "10111"

更新: 上述正则表达式解决方案将0替换为空字符串。为了防止这个问题,请使用以下正则表达式:


var repl = str.replace(/^0+(\d)|(\d)0+$/gm, '$1$2');

正则表达式演示

正则表达式解析:

  • ^: 开始断言
  • 0+: 匹配一个或多个零
  • (\d): 接着匹配并捕获在捕获组#1中的数字
  • |: 或
  • (\d): 匹配并捕获在捕获组#2中的数字
  • 0+: 接着匹配一个或多个零
  • $: 结束断言

替换:

这里我们使用了两个捕获组的反向引用:

$1$2

这基本上是将前导零后的数字和尾随零前的数字放回替换中。


5
我知道这是一个相当古老的帖子,但在谷歌搜索中仍然会显示出来,当尝试修剪前导/尾随零时。虽然这种方法大多数情况下有效,但它不能适当地处理值为“0”的情况。它只是完全将其修剪掉,而0在技术上是一个有效的数字。 - dvsoukup
这个答案真的帮了我很多。但是我无法编写这种数值:1.005 - wonsuc
好的,你错了,我们谈论的是字符串,不是数字,也不是数字字符。 - user192344
抱歉,哪个输入有误,导致这个操作失败了? - anubhava

4
假设输入数据中至少有一个数字,您可以使用以下模式/^0*(\d+?)0*$/与exec()一起使用,并访问单个捕获组。
这只使用一个捕获组,没有备选项(pipes),确保输出中至少有一个数字,并且不寻找多个匹配项(无g)。
捕获组使用懒惰量词,0使用贪婪量词以提高效率。开始和结束锚点(^和$)用于确保整个字符串都匹配。

console.log('0001001000 => '+ /^0*(\d+?)0*$/.exec("00100100")[1]);

console.log('001 => ' + /^0*(\d+?)0*$/.exec("001")[1]);
console.log('100 => ' + /^0*(\d+?)0*$/.exec("100")[1]);

console.log('1 => ' + /^0*(\d+?)0*$/.exec("1")[1]);
console.log('0 => ' + /^0*(\d+?)0*$/.exec("0")[1]);

console.log('11 => ' + /^0*(\d+?)0*$/.exec("11")[1]);
console.log('00 => ' + /^0*(\d+?)0*$/.exec("00")[1]);

console.log('111 => ' + /^0*(\d+?)0*$/.exec("111")[1]);
console.log('000 => ' + /^0*(\d+?)0*$/.exec("000")[1]);

或者你可以将一半的工作交给 + 将字符串转换为整数(这样做的附加好处是在没有长度时稳定输入),然后让 replace 处理右侧修剪。

一次性向后查找 ((?<=\d)) 用于确保输出长度至少为1。 Can I Use: Lookbehind in JS regular expressions

console.log('0001001000 => ' + (+'0001001000'.replace(/(?<=\d)0*$/, "")));
console.log('[empty] => ' + (+''.replace(/(?<=\d)0*$/, "")));

console.log('001 => ' + (+'001'.replace(/(?<=\d)0*$/, "")));
console.log('100 => ' + (+'100'.replace(/(?<=\d)0*$/, "")));

console.log('1 => ' + (+'1'.replace(/(?<=\d)0*$/, "")));
console.log('0 => ' + (+'0'.replace(/(?<=\d)0*$/, "")));

console.log('11 => ' + (+'11'.replace(/(?<=\d)0*$/, "")));
console.log('00 => ' + (+'00'.replace(/(?<=\d)0*$/, "")));

console.log('111 => ' + (+'111'.replace(/(?<=\d)0*$/, "")));
console.log('000 => ' + (+'000'.replace(/(?<=\d)0*$/, "")));


1
我已经点赞你的回答来抵消一下踩票。但是我认为踩票可能是因为你使用了回顾后断言,而这在某些浏览器的JS引擎中不受支持。 - anubhava
哦,我不知道那个。谢谢。 - mickmackusa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接