C#模式搜索
我的下面的代码显示在文件中搜索特定模式….无论如何,我可以添加到此代码,以便我可以搜索可能的四种模式。
因此,如果它与第一个不匹配,那么它会查看它是否与第二个匹配,依此类推……
非常感谢。
byte[] pattern = new byte[5] { 00, 00, 00, 08, 00 }; byte[] file = File.ReadAllBytes("C:\\123.cfg"); var result = Enumerable.Range(0, file.Length - pattern.Length + 1) .Where(i => pattern.Select((b, j) => new { j, b }) .All(p => file[i + pj] == pb)) .Select(i => i + pattern.Length - 1); int[] PatternArray = result.ToArray();
** * ** * ** * **编辑* ** * ** * ** * *
在运行程序时,我插入了一个断点来查看数组存储的内容….这就是它报告的内容
response Count = 6 System.Collections.Generic.List [0] {int[1]} int[] [0] 1577 int [1] {int[0]} int[] [2] {int[0]} int[] [3] {int[0]} int[] [4] {int[0]} int[] [5] {int[6]} int[] [0] 31 int [1] 246 int [2] 448 int [3] 663 int [4] 864 int [5] 1734 int
模式结果似乎都存在,我是否认为这是一个二维数组? ……如果是这样的话,我可以将它放在一个arrays中吗?
非常感谢
创建一个数组(或列表……或其他可枚举的)byte []和一个’匹配’布尔值,然后在模式搜索周围做一个while循环,如下所示:
List patterns = new List() { new byte[] { 00, 00, 00, 08, 00 }, new byte[] { 00, 00, 00, 08, 01 }, new byte[] { 00, 00, 00, 08, 02 }, new byte[] { 00, 00, 00, 08, 03 } }; //bool matched = false; foreach (byte[] pattern in patterns) { //while (!matched) //{ byte[] file = File.ReadAllBytes("C:\\123.cfg"); var result = Enumerable.Range(0, file.Length - pattern.Length + 1) .Where(i => pattern.Select((b, j) => new { j, b }) .All(p => file[i + pj] == pb)) .Select(i => i + pattern.Length - 1); int[] PatternArray = result.ToArray(); // if (result != null) // matched = true; //} }
[edit]这是一个以列表forms返回所有有效匹配的函数:
public List doPatternSearch() { List patterns = new List() { new byte[] { 00, 00, 00, 08, 00 }, new byte[] { 00, 00, 00, 08, 01 }, new byte[] { 00, 00, 00, 08, 02 }, new byte[] { 00, 00, 00, 08, 03 } }; //this becomes a container to hold all of the valid results List response = new List(); foreach (byte[] pattern in patterns) { byte[] file = File.ReadAllBytes("C:\\123.cfg"); var result = Enumerable.Range(0, file.Length - pattern.Length + 1) .Where(i => pattern.Select((b, j) => new { j, b }) .All(p => file[i + pj] == pb)) .Select(i => i + pattern.Length - 1); if (result != null) { //if the result is not null then add it to the list. response.Add(result.ToArray()); } } return response; }
ORegex可以为你做这件事。 以字节顺序搜索模式的一个小例子:
var oregex = new ORegex("{0}{1}{2}", x=> x==12, x=> x==3, x=> x==5); var toSearch = new byte[]{1,1,12,3,5,1,12,3,5,5,5,5}; ^^^^^^ ^^^^^^ var foundTwoMatches = oregex.Matches(toSearch);
您还可以定义IComparable对象并直接传递它,而无需使用labmda函数。
这里有更多例子。