簡體   English   中英

為什么以下正則表達式與此文本匹配?

[英]Why does the following regex match this text?

我有正則表達式:( (?ms)(?<attribute>\\[.+?\\]|public|private|\\s)+?class

我有文字:

[attribute]
public int a;

[attribute C]
[attribute B]
public class Test{

}

我想知道為什么我發布的正則表達式匹配:

[attribute]
public int a;

[attribute C]
[attribute B]
public class

我認為它應該匹配:

[attribute C]
[attribute B]
public class

如果我錯了,請糾正我。 我認為應該讀取正則表達式的方式是:

查找一個屬性([一些屬性])或公共關鍵字或私有關鍵字或空格。

因此,首先,正則表達式引擎應匹配[attribute],然后匹配'\\ n'(換行),然后匹配public關鍵字。 在這些之后,關鍵字int不是一個選項,那么為什么要匹配它呢?

問題是您使用的點與任何內容都匹配,包括右方括號,空格和(在單行模式下)換行符:

\[.+?\]

您應該改用以下代碼:

\[[^\]]+\]

說明:

\[     Match a literal open square bracket.
[^\]]  Match any character except a close square bracket.
+      One or more.
\]     Match a literal close square bracket.

使用此正則Regex

((?<attribute>(?:public|private|\[[^\]]+\]))[\r\n\s]+)*class

並給組命名為attribute 您的代碼可以像這樣:

foreach (Match match in Regex.Matches(inputString, @"((?<attribute>(?:public|private|\[[^\]]+\]))[\r\n\s]+)*class"))
{
    var attributes = new List<string>();
    foreach (Capture capture in match.Groups["attribute"].Captures)
    {
        attributes.Add(capture.Value);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM