Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting a string with regular expressions that contains a certain word anywhere in the string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading