Regex newline and whitespace in golang

Amal Ts picture Amal Ts · Apr 30, 2017 · Viewed 8.3k times · Source

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.)

Answer

Kobi picture Kobi · Apr 30, 2017

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)