golang 中的正则表达式换行符和空格

Regex newline and whitespace in golang

我试图将以下字符串与正则表达式匹配并从中获取一些值。

/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

为此使用了以下正则表达式

`/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`

现在我的问题是:有没有更好的方法呢? 我在字符串中明确提到了每个新行和白色 space 组。但是我可以说 /system.sensor\d\d.*DeviceID=(?P<sensor>.*)\n*. (它对我不起作用,但我相信应该有办法。)

默认情况下 . 不匹配换行符。要更改它,请使用 s 标志:

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

发件人:RE2 regular expression syntax reference

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

如果你想以更短的方式使用正则表达式获得这些属性,你想首先使用 (?s) [Kobi 的回答中的含义和用途]。对于每个 属性 使用此语法:
.*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.

所以,这是一个简短的正则表达式,它将匹配您的文本并获得所有这些属性:

(?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

[演示]: https://regex101.com/r/Awgqpk/1