P
P
Paul Smith @Paul2013-03-04 12:10:05
Regular Expressions
Paul Smith @Paul, 2013-03-04 12:10:05

Replacing digits in regular expressions

There is a file with a bunch of lines of text:

fillColor: 'rgb(R,G,B)'

Where R,G,B are three-digit numbers. It is

necessary to decrease the values ​​of channels G and B (ie, decrease the last 2 digits in brackets) by the same values.
I'm looking for the substring like this:

rgb\(([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3})\)


How to make a replacement now so that rgb(R, G-50, B-50) is displayed?
Those. so that G-50 is not a string, namely, 50 is subtracted from the number and substituted in place of G.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
UZER2006, 2013-03-04
@UZER2006

Regardless of the runtime environment, there is no way to calculate the whole thing using the regexp itself. It is necessary to receive a string (or parts recognized by a regular expression), read and form a finished string for output.
Alternatively, JS has a callback method: String.replace(<expression>,function(value){}).Callback is called for each match, and the match itself is replaced by the value returned by the function.

A
avalak, 2013-03-04
@avalak

Sketched a variant for Python.

#!/usr/bin/env python2

import re

with open("source_raw.txt") as f:
    source_raw=f.read()

def repl(m):
    def fix(v, delta=50):
        n = int(v) - delta
        return n if n >= 0 else 0

    return "rgb({r},{g},{b})".format(r=m.group(1), g=fix(m.group(2)), b=fix(m.group(3)))

source=re.sub(r'rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)', repl, source_raw)

with open("source.txt", "w") as f:
    f.write(source)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question