简体   繁体   English

正则表达式:删除前导零,但保留单个零

[英]regex: remove leading zeros, but keep single zero

I have an input field to which I have tied a formatting function that is triggered whenever the field loses focus.我有一个输入字段,我绑定了一个格式化函数,该函数在该字段失去焦点时触发。

What I aim to achieve is that I remove all the leading zeros from an input and I did achieve that with the below line.我的目标是从输入中删除所有前导零,并且我确实使用以下行实现了这一点。 However, when the user wants to enter a single 0 or something like 0000 I still want that field to end with the value 0 (single).但是,当用户想要输入单个 0 或类似 0000 的内容时,我仍然希望该字段以值 0(单个)结尾。 With .replace(/^0+/, '') it would remove every zero and return just an empty string.使用.replace(/^0+/, '')它将删除每个零并只返回一个空字符串。 Someone knows what regex could handle this?有人知道什么正则表达式可以处理这个吗?

const formatNumber = ($field) => {
var number = $field.val().replace(/\./g, '').replace(/\s/g, '').replace(/^0+/, '');
return number;
};

note : if(number === "") number = "0" is not an option.注意if(number === "") number = "0"不是一个选项。

edit1: : I noticed there seems to be a bit of confusion.编辑1::我注意到似乎有点混乱。 eg "0009825" need to become 9825 and not 09825. the only instance where i want a 0 up front is when the value is simply zero.例如,“0009825”需要变为 9825 而不是 09825。唯一需要预先设置为 0 的情况是该值为零。

You ay use this regex replacement:您可以使用此正则表达式替换:

.replace(/^(?:0+(?=[1-9])|0+(?=0$))/mg, '')

RegEx Demo正则表达式演示

RegEx Details:正则表达式详情:

  • ^ : Start ^ : 开始
  • (?: : Start capture group (?: : 开始捕获组
    • 0+(?=[1-9]) : Match 1 or more zeroes that must be followed by 1-9 0+(?=[1-9]) :匹配 1 个或多个必须后跟1-9
    • | : OR : 或者
    • 0+(?=0$) : Match 1 or more zeroes that must be followed by one 0 and end 0+(?=0$) :匹配 1 个或多个必须后跟一个0并结束的零
  • ) : End capture group ) : 结束捕获组

Replacement is empty string which will leave a single 0 if there are only zeroes in string otherwise will remove leading zeroes.替换是空字符串,如果字符串中只有零,则将留下单个0 ,否则将删除前导零。


Alternative solution using a capture group:使用捕获组的替代解决方案

str = str.replace(/^0+(0$|[1-9])/mg, '$1');

A simple reg exp with leading zeros and match one digit in a capture group带有前导零并匹配捕获组中的一位数字的简单正则表达式

 const cleanZeros = str => str.replace(/^0+(\\d)/, '$1') var tests = ["0009876","0", "0000", "9999", "0090000"] tests.forEach( s => console.log(s, cleanZeros(s)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM