[英]Find where Regex.Match failed
我想知道哪個Regex Groupcollection無法匹配。
例如:
我的模式通過以下方式檢測VIEW start page
或VIEW end
:
match = Regex.Match(string, @"(^VIEW)\s*((?(1)(?:(start)\s*((?(1)page$))|(end$))))");
我想知道我是否將輸入字符串作為“VIEW go”如何找到第二組失敗。
您不必檢查后一組以驗證您的正則表達式是否與某些內容匹配。
方法返回的匹配對象允許您使用以下方法檢查:
if ( match.Success )
Console.Write("Success!");
else
Console.Write("Expected start page or end after VIEW");
為了您的目的,您還可以簡化您的正則表達式:
match = Regex.Match(string, @"^VIEW\s+(?:start\s+page|end)$");
請參閱在線演示 。
UPDATE
如果要優化錯誤消息,可以嘗試以下方法:
match = Regex.Match(string, @"^VIEW\s+(?:(start\s+page|end)|(.*))$");
if (match.Success) {
if ( match.Groups[1].Success)
Console.Write("Success!");
if ( match.Groups[2].Success)
Console.Write("Expected start page or end after VIEW");
} else {
Console.Write("usage: VIEW [start page|end]");
}
關於ideone的運行代碼演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.