Skip to content
Advertisement

Regex (JS) : character appears no more than N times

I have the following string :

JavaScript

In this string, I would like to replace the 0s that appear less than 6 times one after the other. If they appear 6 times or more, I would like to keep them.

(Replace them with a dot for instance)

The end result should then be

JavaScript

I thought about using the negative lookahead and tried it, but I’m not sure how it works in that particular use-case.

Would someone be able to help me ?

My current, not working regex is

JavaScript

EDIT

After playing around a bit, I found this regex :

JavaScript

but it captures the 1 before the 0s. Would there be a way to exclude this 1 from getting caught in the regex ?

Advertisement

Answer

With Javascript, if a positive lookbehind is supported and with the global flag:

JavaScript

Explanation

  • (?<= Positive lookbehind, assert to the left
    • (?:1|^) Match either 1 or start of the string
    • (?!0{6}) Negative lookahead, assert not 6 zeroes
    • 0{0,4} Match 0-4 times a zero
  • ) Close the lookbehind
  • 0 Match a zero

Regex demo

In the replacement use a dot.

Advertisement