Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex newline and whitespace in golang

Tags:

regex

go

re2

I was trying to match the below string with a regex and get some values out of it.

/system1/sensor37
  Targets
  Properties
    DeviceID=37-Fuse 
    ElementName=Power Supply
    OperationalStatus=Ok
    RateUnits=Celsius
    CurrentReading=49
    SensorType=Temperature
    HealthState=Ok
    oemhp_CautionValue=100
    oemhp_CriticalValue=Not Applicable

Used the below regex for that

`/system1/sensor\d\d\n.*\n.*\n\s*DeviceID=(?P<sensor>.*)\n.*\n.*\n.*\n\s*CurrentReading=(?P<reading>\d*)\n\s*SensorType=Temperature\n\s*HealthState=(?P<health>.*)\n`

Now my question is: Is there a better way to do it? I explicitly mentioned each new line and white space group in the string. But can I just say /system.sensor\d\d.*DeviceID=(?P<sensor>.*)\n*. (It didn't work for me, but I believe there should be a way to it.)

like image 897
Amal Ts Avatar asked Dec 01 '22 11:12

Amal Ts


2 Answers

By default . does not match newlines. To change that, use the s flag:

(?s)/system.sensor\d\d.*DeviceID=(?P<sensor>.*)

From: RE2 regular expression syntax reference

(?flags) set flags within current group; non-capturing
s - let . match \n (default false)

like image 124
Kobi Avatar answered Dec 05 '22 06:12

Kobi


If you want to get these properties using regex in a shorter way, you'd like to firstly use (?s) [Meaning & use in Kobi's answer]. And for each property use this syntax:
.*ExampleProperty=(?P<example>[^\n]*).*:

.* - "Ignores" all text at the beginning and at the end (Match, but doesn't capture);
ExampleProperty= - Stop "ignoring" the text;
(?P<example>...) - Named capture group;
[^\n*] - Matches the value from the property till it find a new line character.

So, this is the short regex that shall match your text and get all these properties:

(?s)\/system.\/sensor\d\d.+DeviceID=(?P<sensor>[^\n]*).*CurrentReading=(?P<reading>[^\n]*).*SensorType=(?P<type>[^\n]*).*HealthState=(?P<health>[^\n]*).*

<sensor> = 37-Fuse 
<reading> = 49
<type> = Temperature
<health> = Ok

[DEMO]: https://regex101.com/r/Awgqpk/1

like image 24
Mateus Avatar answered Dec 05 '22 08:12

Mateus