I am having a hard time understanding regex syntax for this specific issue I am facing. I am using Python.
Here is a sample output (with random values) of sensors I am using that is in a txt file:
Sensors starting
{'device_id': 'M123'}
{'x_acc': 0.00, 'y_acc' : 0.01, 'z_acc' : 1.02}
But from another device I am getting it like this:
Sensors starting
{'device_id': 'S123'}
{'y_acc': 0.00, 'z_acc' : 0.01, 'x_acc' : 1.02}
What I want to do is extract anything between { and } with, lets say, ‘x_acc’ in it so it detects both strings and doesnt select the line with the device ID as it gets printed multiple times in the same file every few minutes.
I was able to come up with this pattern:
pattern = r'\{.*?\}'
To select the lines with { } but I want to specify the lines with x_acc, y_acc or z_acc in them to be selected. I was able to do if I know the first item and add it to the pattern but since the order changes from one device to another I am not sure how to do it.
>Solution :
You can use
{[^{}]*'[xyz]_acc'[^{}]*}
See the regex demo.
Details:
{– a{char[^{}]*– zero or more chars other than curly braces'[xyz]_acc'– a'char, then ax,yorzchar, and then a_acc'substring[^{}]*– zero or more chars other than curly braces}– a}char.