Pregunta

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.

¿Fue útil?

Solución

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

This will return Static

Otros consejos

You can try a different pattern:

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

I am assuming that Type = is always followed by a new line that starts with a semicolon ;.

Thanks for @SimonWhitehead and @HamZa for reminding me, I should note that this will capture both Type = lines, so you need to ignore the first match and look for the second one only.

EDIT: You can try another expression, which is not as efficient as the first one:

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

RegexHero Demo

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top