简体   繁体   中英

Match using first part of regex if decimal exists and second part if none

I'm trying to match the leading zeros of a string to replace with an empty string. I can have a scenario with leading zeros such that there is a decimal: 0000000.005 or without: 000000000005 .

I've come up with: /.+?(?=0\\.)|.+?(?=[0-9]+)/ .

The first part matches all the leading zeroes up until I reach a 0. pattern (ie 0000000.005 becomes 0.005 ). The second part applies the same lazy, positive lookahead approach to leading zeros without a decimal (ie 000000000005 becomes 5 ).

Since the second part ( .+?(?=[0-9]+) ) is stronger than the first, it will always turn 0000000.005 into 5 . Is there a way to, in one expression, only match using the first section if there is, say the presence of a decimal, and to use the other expression if not?

Thanks!

If you need a regex solution, you may use

s.replace(/^0+(?=0\.|[1-9])/, '')

See the regex demo .

Details

  • ^ - start of string
  • 0+ - 1+ zeros
  • (?=0\\.|[1-9]) - the next chars should be 0. or a digit from 1 to 9 .

JS demo:

 var strs = ['000000000005', '0000000.005']; for (var s of strs) { console.log(s, '=>', s.replace(/^0+(?=0\\.|[1-9])/, '')); console.log(s, '=>', Number(s)); // Non-regex way }

You can use the replace() fucntion in regex.
Here is the demo code .

 var str = "00000000.00005"; var str1 = "0000000005"; if(str.includes(".")) //case 1 { str = str.replace(/0+\\./g, '0.'); console.log("str ==>", str); } if(!str1.includes("."))//case 2 . { str1 = str1.replace(/0+\\.|0+/g, ''); console.log("str 1 ===>", str1); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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