[英]C# Regular Expression Match Failing
這是正則表達式模式:
string testerpattern = @"\s+\d+:\s+\w\w\w\w\w\w\s+..:..:..:..:..:..:..:..\s+\d+.\d+.\d+.\d+\s+\d+.\d+.\d+.\d+\s+""\w +""";
這是我要匹配的幾行文字。 行首將有1個或多個空格。 當它運行時,我將對其進行修改以進行命名匹配。 基本上,我希望大部分行不對每個模式的一行進行多次匹配。
2: fffc02 10:00:00:05:1e:36:5f:82 172.31.3.93 0.0.0.0 "SAN002A"
3: fffc03 10:00:00:05:1e:e2:a7:00 172.31.3.168 0.0.0.0 "SAN003A"
4: fffc04 50:00:51:e8:cc:2f:ae:01 0.0.0.0 0.0.0.0 "fcr_fd_4"
這是我寫來進行比賽的靜態課程。 它可以在程序的其他地方工作,所以我假設這是一個有問題的模式。 該模式在Regexr.com上成功匹配
public static class RegexExtensions
{
public static bool TryMatch(out Match match, string input, string pattern)
{
match = Regex.Match(input, pattern);
return (match.Success);
}
public static bool TryMatch(out MatchCollection match, string input, string pattern)
{
match = Regex.Matches(input, pattern);
return (match.Count > 0);
}
}
首先,如果要匹配一個或多個單詞字符,請務必刪除\\w
和+
之間的空格。
接下來,如果需要匹配文字點,則必須對它進行轉義- \\.
,或放入字符類- [.]
。
此外, 如果不需要捕獲 ,可以使用限制量詞來縮短模式。 查看如何編寫模式:
string pat = @"\s+\d+:\s+\w{6}\s+(?:..:){7}..(?:\s+\d+(?:\.\d+){3}){2}\s+""\w+""";
請參見regex演示 (其中\\w{6}
匹配6個“單詞”字符, (?:..:){7}
匹配7個2個字符的序列,除了換行符后跟:
等)。
如果仍然需要捕獲 ,則可以使用我上面概述的想法:
\s+(\d+):\s+(\w{6})\s+(..(?::..){3}):((?:..:){3}..)\s+(\d+(?:\.\d+){3})\s+(\d+(?:\.\d+){3})\s+"(\w+)"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.