-1

I've two string that and I would like to replace the numbers that located after the first comma in the first []. Please note that the numbers may change and are not fixed numbers.

However, I could change the numbers for phase_y. but in phase_x it replace the first two number after that comma and also replace the numbers that located after the [Ego: which i don't want that. I would like to see the other numbers remain expect the first two numbers after in the first []. I don't know why is my regex works for the phase_y and not works for the phase_x. any hlep?

import os
import random
 
import re
 

 
phase_x = "PHASE 1: [Drive_Towards] [-, 24 to 34, -4 to -3][Ego: -10 to 0, FSR]"
phase_y = "PHASE 1: [Walk_Towards] [-, 1 to 3, -3 to -5][Ego:-4 to -2, FSL]"
LowerValue = 10
HigherValue = 20
 
 
 
myRegex_1 = "\d+\sto\s\d+"
myRegex_2 = str(LowerValue)+" to "+ str(HigherValue)
 
 
 
new_line_phase_x = re.sub(myRegex_1, myRegex_2, phase_x)
new_line_phase_y = re.sub(myRegex_1, myRegex_2, phase_y)
 
print(new_line_phase_x)
print(new_line_phase_y)

Python demo here

  • You can try using a grouped regex, as per [this answer](https://stackoverflow.com/questions/14007545/python-regex-instantly-replace-groups). – niid Aug 15 '22 at 14:55
  • @niid I'm very much new to regex, would you please explain more? – user19640240 Aug 15 '22 at 15:20

1 Answers1

1

As far as I understood, you want the change only once, that also after the first [] and comma in both phase_x and phase_y. Add another parameter count=1 , in your re.sub() command to change only once.

new_line_phase_x = re.sub(myRegex_1, myRegex_2, phase_x,1)
new_line_phase_y = re.sub(myRegex_1, myRegex_2, phase_y,1)

This gives output

PHASE 1: [Drive_Towards] [-, 10 to 20, -4 to -3][Ego: -10 to 0, FSR]
PHASE 1: [Walk_Towards] [-, 10 to 20, -3 to -5][Ego:-4 to -2, FSL]

mrin9san
  • 305
  • 1
  • 2
  • 12