Regex newline and whitespace in golang

10,156

Solution 1

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)

Solution 2

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

Share:
10,156
Amal Ts
Author by

Amal Ts

DevOps Engineer @ the "World's Most Innovative Company" - Salesforce.com Startup Enthusiast

Updated on June 12, 2022

Comments

  • Amal Ts
    Amal Ts almost 2 years

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