0

I have been searching all day on Stackoverflow and many other sites, but I just can't seem to wrap my head around trying to get regex to match what I need.

Please see example below:

This is the text I'm searching.

[Date]
;Possible values: Local, Static
;Type = Local
;If using Static type, the year/month/date to set the date to
;Year = 2012
;Month = 1
;Date = 1

[Time]
;Possible values: Local, Custom, Static
Type = Static
;If using Custom type, offset from UTC in hours (can be negative as well)
Offset = 0
;If using Static type (Hour value always the same on every server start), the value (0-24) to set the Hour to
Hour = 9

What I am trying to accomplish is a lookahead and obtain only the Type = Static under the [Time] bracket. I am using C# if that helps. I have tried many many different patterns with no success.

(?<=\[Time\]\n+Type = ).* 
(?<=\[Time\].*Type =).*

That's just a few ideas that I have tried. Can someone please show me the correct way to do this with an explanation on why it is doing what its doing? Based on the comments I noticed that I should be more clear on the fact that this file is much larger then what I have shown and almost each [SETTING] contains atleast one type flag to it. Also its almost 100% sure that the user will have ;comments put into the file so I have to be able to search out that specific [SETTING] and type to make it work.

4

2 回答 2

2
var val = Regex.Match(alltext, 
                      @"\[Time\].+?Type\s+=\s+([^\s]+)", 
                      RegexOptions.Singleline)
              .Groups[1].Value;

这将返回静态

于 2013-10-16T21:49:28.100 回答
0

您可以尝试不同的模式:

(?<=Type\s*=\s*).*(?=[\r\n;]+)

我假设Type =后面总是跟一个以分号开头的新行;

感谢@SimonWhitehead 和@HamZa 提醒我,我应该注意这将捕获两条Type =线,因此您需要忽略第一个匹配项并仅查找第二个匹配项。

编辑:您可以尝试另一个表达式,它不如第一个有效:

(?<=\[Time\][\r\n;]*[^\r\n]+[\r\n]*Type\s*=\s*).*

RegexHero 演示

于 2013-10-16T21:34:21.787 回答