Answer the question
In order to leave comments, you need to log in
Replacing digits in regular expressions
There is a file with a bunch of lines of text:
fillColor: 'rgb(R,G,B)'
rgb\(([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3})\)
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question