【问题标题】:Remove leading and trailing zeros from a string从字符串中删除前导零和尾随零
【发布时间】:2025-12-22 04:30:12
【问题描述】:

我有几个这样的字符串:

str1 = "00001011100000";  // 10111
str2 = "00011101000000";  // 11101
...

我想使用带有 ONE 操作的正则表达式从每个字符串中去除前导和结束零。

到目前为止,我使用了两个不同的功能,但我想将它们组合在一起:

str.replace(/^0+/,'').replace(/0+$/,'');

【问题讨论】:

    标签: javascript jquery regex string


    【解决方案1】:

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

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

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

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

    RegEx Demo

    RegEx 拆分:

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

    替换:

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

    $1$2
    

    这基本上将数字放在前导零之后,将数字放在尾随零之前。

    【讨论】:

    • 我知道这是一个非常古老的线程,但在尝试修剪前导/尾随零时,它仍然出现在谷歌搜索中。虽然这在大多数情况下都有效,但它不能正确处理“0”的值。它只是将其完全修剪掉,而 0 在技术上是一个有效的数字。
    • 这个答案对我很有帮助。但是我不能写这些值:1.005
    • 好吧,你错了,我们说的是字符串,不是数字,不是数字
    • 抱歉,谁不正确,哪些输入无效?
    【解决方案2】:

    假设您在输入数据中始终至少有一位数字,您可以将此模式 /^0*(\d+?)0*$/exec() 一起使用并访问单个捕获组。

    这仅使用一个捕获组,没有替代项(管道),并确保输出中至少有一位数字,并且不寻求多个匹配项(无 g)。

    捕获组使用惰性量词,0s 使用贪婪量词以提高效率。开始和结束锚点(^$)用于确保匹配整个字符串。

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

    或者您可以将一半的工作转移到 + 以将字符串强制转换为 int(这具有在没有长度时稳定输入的额外好处),然后让 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*$/, "")));

    【讨论】:

    • 我赞成您的回答以消除反对票。但是我认为downvote可能是因为您使用了所有浏览器的JS引擎都不支持的lookbehind。
    • 哦。我不知道。谢谢