Home > database >  RegEx: replace multiple values in text
RegEx: replace multiple values in text

Time:01-10

I have a text file where each line contains specific values. They change often. I’d like to replace two values on a single line in one go without rewriting the entire line.


Current regex pattern:
(\(Psig\)- )(\d \.\d )

Regex to do one value at a time:
^(.*?(.*?\(Psig\)- ){1})(\d \.\d )

Using \1 backreference to change values

Line from file:

RPM- 1400, (Psig)- 57.66, Ts- 48.11, (Psig)- 299.33

I currently want to change the values that follows (Psig)- , currently pattern both values that I need to change but when using back reference it changes both values to same thing.

In this example:

57.66-> 22.77

299.33-> 355.26

I was thinking to use re.sub() to replace these values. Is this possible to do with this method or is there another option to do this?

CodePudding user response:

Assuming there are only two matches in the line, would you please try the following:

#!/usr/bin/python

import re

s = 'RPM- 1400, (Psig)- 57.66, Ts- 48.11, (Psig)- 299.33'
newval = ['22.77', '355.26']            # array of new values
val_iter = iter(newval)                 # iterator to return each new value

s = re.sub(r'(?<=\(Psig\)- )[\d.] ', lambda x: next(val_iter), s)
print(s)

Output:

RPM- 1400, (Psig)- 22.77, Ts- 48.11, (Psig)- 355.26

The regex (?<=\(Psig\)- )[\d.] matches a decimal value preceded by the string (Psig)- . Each time the regex matches, the value is replaced with the output of the iterator.

  •  Tags:  
  • Related