Skip to content
Advertisement

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

I have the following string :

11110000111100000000111100001111000000

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

1111....1111000000001111....1111000000

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

/(?!0{6,})0{1,5}/g

EDIT

After playing around a bit, I found this regex :

/((?:^|1)(?!0{6,})0{1,5})/g

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:

/(?<=(?:1|^)(?!0{6})0{0,4})0/g

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