我不是regex的专家,我需要一些帮助来建立一个。
我使用的是Powershell及其regex类型,这是一个C#类,最终目标是读取一个toml文件(底层的示例数据,或者使用这个链接到regex101),在其中我需要:
为了匹配这些值并将它们放入捕获组,以下regex工作:
match the template value (values between "__" ):
__(?<tokenName>[\w\.]+)__我也想忽略那些评论行,我想出了以下内容:
Ignore lines that start with a comment (even if "#" is preceded by spaces or tabs):
^(?!\s*\t*#).*当我把它们放在一起时,问题就开始了。
^(?!\s*\t*#).*__(?<tokenName>[\w\.]+)__该表达式存在以下问题:
我也试过
add this at the end of the expression, it should stop the match on the first occurrence of the character
[^#]
add this at the beginning, which should check if the matched string has the given char before it and exclude it
(?<!^#)这是我的数据样本
#templateFile
[Agent]
Prop1 = "__Data.Agent.Prop1__"
Prop2 = [__Data.Agent.Prop2__]
#I'm a comment
#Prop3 = "__NotUsed__"
Prop4 = [__Data.Agent.Prop4__] #sample usage comment __Data.Agent.xxx__
Prop5 = ["__Data.Agent.Prop5a__","__Data.Agent.Prop5b__"]我认为更容易的解决方案是匹配给定的字符串,只有在同一行的字符串之前没有"#“。有可能吗?
编辑:
@ The -4-bird提出的第一个表达式工作得很好,它只需要指定多行修饰符。最后(可运行的)结果在PowerShell中如下所示。
[regex]$reg = "(?m)(?<!^.*#.*)__(?<tokenName>[\w.]+)__"
$text = '
#templateFile
[Agent]
Prop1 = "__Data.Agent.Prop1__"
Prop2 = [__Data.Agent.Prop2__]
Prop5 = ["__Data.Agent.Prop5a__","__Data.Agent.Prop5b__"]
#a comment
#Prop3 = "__Data.Agent.Prop3__"
Prop4 = [__Data.Agent.Prop4__] #sample usage comment __Data.Agent.xxx__
'
$reg.Matches($text) | Format-Table
#This returns
Groups Success Name Captures Index Length Value
------ ------- ---- -------- ----- ------ -----
{0, tokenName} True 0 {0} 31 20 __Data.Agent.Prop1__
{0, tokenName} True 0 {0} 62 20 __Data.Agent.Prop2__
{0, tokenName} True 0 {0} 94 21 __Data.Agent.Prop5a__
{0, tokenName} True 0 {0} 118 21 __Data.Agent.Prop5b__
{0, tokenName} True 0 {0} 194 20 __Data.Agent.Prop4__发布于 2020-01-22 17:51:25
我认为您可以使用无限重复来检查前面的内容是否包含一个#来解释Prop4中的注释。
(?<!^.*#.*)__(?<tokenName>[\w.]+)__.Net regex演示
如果Prop4应该有两个匹配项,则可以使用:
(?<!^[ \t]*#.*)__(?<tokenName>[\w.]+)__.NET regex演示
这两个表达式都需要多行修饰符才能正常工作。它可以通过在开头添加(?m)来内联指定。(或者通过在支持它的构造函数中指定它)
(?m)(?<!^.*#.*)__(?<tokenName>[\w.]+)__https://stackoverflow.com/questions/59865142
复制相似问题