繁体   English   中英

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`

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

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

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

来自: RE2正则表达式语法参考

(?flags)在当前组中设置标志; 非捕获
s - 让. 匹配\\n (默认为false)

如果你想以较短的方式使用正则表达式获得这些属性,你首先要使用(?s) [在Kobi的答案中使用和意义]。 对于每个属性使用以下语法:
.*ExampleProperty=(?P<example>[^\\n]*).*

.* - “忽略” 开头结尾的所有文本(匹配,但不捕获);
ExampleProperty= - 停止“忽略”文本;
(?P<example>...) - 命名捕获组;
[^\\n*] - 匹配属性中的值,直到找到新的行字符。

因此,这是与您的文本匹配并获得所有这些属性的短正则表达式:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM