Randy Hall
Randy Hall

Reputation: 8127

Replace only part of match

I have a regex that currently looks like this:

/((0{32})([0-1]{48}){16})/

Basically, match "0" 32 times, then "0" or "1" 48 times, then that pattern 16 times. Seems to be working for str.match().

What I'm trying to do is replace the "0"s matched only in that first part (the 32, each of the 16 times) with "1", but not the "0"s matched in the second part (the [0-1] range of 48).

I cannot seem to wrap my head around how to accomplish that today.

The regex pattern is separately generated, but the string it matches will always contain only "0"s and "1"s. Yes, I'm sure this seems weird, but this is exactly what I need to happen.

Upvotes: 2

Views: 187

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

You need to use a positive lookahead to assert that the 32 zeros must be followed by the 48 ones and zeros, but not actually capture them. For instance:

/((0{32})(?=([0-1]{48}){16}))/

Upvotes: 3

Related Questions