Home > Software design >  Extracting a string with regular expressions that contains a certain word anywhere in the string
Extracting a string with regular expressions that contains a certain word anywhere in the string

Time:05-27

I am having difficulty 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, let's say, 'x_acc' in it so it detects both strings and doesn't 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 chosen. I was able to do it when I knew the first item - then I added it to the pattern, but since the order changes from one device to another, I am not sure how to do it.

CodePudding user response:

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 a x, y or z char, and then a _acc' substring
  • [^{}]* - zero or more chars other than curly braces
  • } - a } char.
  • Related