简体   繁体   中英

Javascript Regex: negative lookbehind

I am trying to replace in a formula all floating numbers that miss the preceding zero. Eg:

"4+.5" should become: "4+0.5"

Now I read look behinds are not supported in JavaScript, so how could I achieve that? The following code also replaces, when a digit is preceding:

 var regex = /(\\.\\d*)/, formula1 = '4+1.5', formula2 = '4+.5'; console.log(formula1.replace(regex, '0$1')); //4+10.5 console.log(formula2.replace(regex, '0$1')); //4+0.5 

Try this regex (\\D)(\\.\\d*)

 var regex = /(\\D)(\\.\\d*)/, formula1 = '4+1.5', formula2 = '4+.5'; console.log(formula1.replace(regex, '$10$2')); console.log(formula2.replace(regex, '$10$2')); 

You may use

s = s.replace(/\B\.\d/g, '0$&')

See the regex demo .

Details

  • \\B\\. - matches a . that is either at the start of the string or is not preceded with a word char (letter, digit or _ )
  • \\d - a digit.

The 0$& replacement string is adding a 0 right in front of the whole match ( $& ).

JS demo:

 var s = "4+1.5\\n4+.5"; console.log(s.replace(/\\B\\.\\d/g, '0$&')); 

Another idea is by using an alternation group that matches either the start of the string or a non-digit char, capturing it and then using a backreference:

 var s = ".4+1.5\\n4+.5"; console.log(s.replace(/(^|\\D)(\\.\\d)/g, '$10$2')); 

The pattern will match

  • (^|\\D) - Group 1 (referred to with $1 from the replacement pattern): start of string ( ^ ) or any non-digit char
  • (\\.\\d) - Group 2 (referred to with $2 from the replacement pattern): a . and then a digit

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