RebelAlliance RebelAlliance - 1 month ago 4
Python Question

In Python, matching the first occurrence of a word AFTER the occurrence of another word

I am attempting to replace the occurrence of a word that occurs only after another word in a JSON text string. I have been struggling to use regular expressions to do this but using just Python functions will be fine with me.

So what I want is to find the first occurrence of

"LEVEL1"
: (with quotes), then find first occurrence of
"session_transition":
, then find whatever string is in quotes after
"session_transition":
, and then replace it with another string. Here is the string I am working with:

"BASELINE": {
"audio_volume": 150,
"cry_threshold": 70,
"cry_transition": "LEVEL1",
"expected_volume": 63,
"led_color": "BLUE",
"led_blink_speed": "NONE",
"motor_amplitude": 0.97,
"motor_frequency": 0.5,
"power_transition": "SUSPENDED",
"seconds_to_ignore_cry": 10.0,
"seconds_in_state": -1.0,
"session_transition": "ONLINE",
"track": "RoR",
"timer_transition": null,
"active_session" : 1
},
"LEVEL1": {
"audio_volume": 300,
"cry_threshold": 75,
"expected_volume": 63,
"cry_transition": "LEVEL2",
"led_color": "PURPLE",
"led_blink_speed": "NONE",
"motor_amplitude": 0.76,
"motor_frequency": 1.20,
"power_transition": "SUSPENDED",
"seconds_to_ignore_cry": 10.0,
"seconds_in_state": 480.0,
"session_transition": "ONLINE",
"track": "RoR",
"timer_transition": "BASELINE",
"active_session" : 1
}


}

For instance, below I want to find and replace
"ONLINE"
under
"LEVEL1":
-->
"session_transition":
to
"OFFLINE"
so it'll look like this:

"LEVEL1": {
"audio_volume": 300,
"cry_threshold": 75,
"expected_volume": 63,
"cry_transition": "LEVEL2",
"led_color": "PURPLE",
"led_blink_speed": "NONE",
"motor_amplitude": 0.76,
"motor_frequency": 1.20,
"power_transition": "SUSPENDED",
"seconds_to_ignore_cry": 10.0,
"seconds_in_state": 480.0,
"session_transition": "OFFLINE",
"track": "RoR",
"timer_transition": "BASELINE",
"active_session" : 1
}


So far I have
r"(?<=\"LEVEL1\"\:).*
to match the first occurrence but don't know how to proceed further.

Answer

I think you can do this somewhat easily using string.index()

first_index = some_string.index("\"Level1\"')
second_index = some_string[first_index:].index("\"Online"\")

after that I leave it up to you to replace the string. You should be able to do it using some_string[second_index:].split('"') and then use splicing and join to put it back together.

Comments