简体   繁体   English

多行正则表达式问题

[英]Multi Line Regex Issue

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. 我一直在Stackoverflow和许多其他网站上搜索,但我似乎无法试图让正则表达式匹配我需要的东西。

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. 我想要完成的是前瞻,只获得[时间]括号下的Type = Static。 I am using C# if that helps. 我正在使用C#,如果这有帮助。 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. 基于这些评论,我注意到我应该更清楚这个文件比我显示的要大得多,而且几乎每个[SETTING]都包含至少一个类型的标志。 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. 此外,它几乎100%确定用户将拥有;注释放入文件中,因此我必须能够搜索特定的[设置]并键入以使其工作。

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

This will return Static 这将返回静态

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 ; 我假设Type =后面跟着一个以分号开头的新行; .

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. 感谢@SimonWhitehead和@HamZa提醒我,我应该注意这将捕获Type =行,因此您需要忽略第一个匹配并仅查找第二个匹配。

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 RegexHero演示

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

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