[英]Remove leading and trailing zeros from a string
我有几个这样的字符串:
str1 = "00001011100000"; // 10111
str2 = "00011101000000"; // 11101
...
我想使用带有 ONE 操作的正则表达式从每个字符串中去除前导和结束零。
到目前为止,我使用了两个不同的函数,但我想将它们组合在一起:
str.replace(/^0+/,'').replace(/0+$/,'');
您可以使用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
这基本上将数字放在前导零之后,将数字放在尾随零之前放回替换中。
假设您在输入数据中总是至少有一位数字,您可以使用这种模式/^0*(\\d+?)0*$/
和exec()
并访问单个捕获组。
这仅使用一个捕获组,没有替代项(管道),并确保输出中至少有一位数字,并且不会寻找多个匹配项(没有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]);
或者,您可以将一半的工作转移到+
以将字符串转换为 int(这具有在没有长度时稳定输入的额外好处),然后让replace
处理右侧修剪。
一次性回溯 ( (?<=\\d)
) 用于确保最小输出长度为 1。 我可以使用:在 JS 正则表达式中回溯
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*$/, "")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.