MGX
MGX

Reputation: 3521

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 ?

Upvotes: 1

Views: 85

Answers (2)

The fourth bird
The fourth bird

Reputation: 163277

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.

Upvotes: 3

bobble bubble
bobble bubble

Reputation: 18490

Javascript replace can take a function as replacement, e.g.:

let res = s.replace(/0+/g, m => {
  return (x = m.length) < 6 ? '.'.repeat(x) : m;
});

See this demo at tio.run

There is not much to explain. Matching one or more 0. If the match is below 6 characters, return a string composed of its length repeated replacement character, else return the full match.

Upvotes: 5

Related Questions