【问题标题】:How to match regular expression with hex value?如何将正则表达式与十六进制值匹配?
【发布时间】:2017-06-17 08:18:24
【问题描述】:

我有这样的文本文件:

1:upx1:4D 00 68 6B 6A 68 6A:True
2:upx2:68 6B ?? 68 6A 00 02:False
3:upx3:FF 4D ?? 68 6B ?? 68:True

我有这样的字符串:

4D 5A 02 68 6B 6A

与第 3 行匹配的人

我使用此代码检查正则表达式路径:

string readdb(string hash)
{
    using (StreamReader sr = new StreamReader("db.txt"))
    {
        string re = string.Format(@"(?<row>\w*:)(?<title>\w*:)({0}:)(?<ep>\w*)", hash);

        String line;
        while ((line = sr.ReadLine()) != null)
        {
            Regex regex = new Regex(re);
            Match match = regex.Match(line);
            if (match.Success)
            {
                return match.Groups[3].Value.ToString();
            }
        }
        return "0";

    }

}

但是我的问题是 ??登录文件!
如何匹配任何十六进制值而不是双问号?

【问题讨论】:

  • 3:upx3:FF 4D ?? 68 6B ?? 68:True 如何匹配4D 5A 02 68 6B 6A
  • 仅将“FF 4D ?? 68 6B ?? 68”与“4D 5A 02 68 6B 6A”匹配
  • 如果hash4D 5A 02 68 6B 6A,则传递给re string.Join(" ", hash.Split().Select(x=&gt;string.Format(@"(?:{0}|\?\?)", x))),参见what regex will look like
  • 顺便说一句,Regex regex = new Regex(re); 必须在 while 循环之前声明。

标签: c# regex hex


【解决方案1】:

首先,将Regex regex = new Regex(re); 移动到while 循环之前,您将避免正则表达式对象重新生成相关的性能问题。

接下来,您似乎需要 2 个十六进制字符的确切序列 OR 一个双问号。您可以准备您的 hash 变量,以便它可以按照上述方式进行匹配:

hash = string.Join(" ", hash.Split().Select(x=>string.Format(@"(?:{0}|\?\?)", x)).ToArray());
string re = string.Format(@"(?<row>\w*):(?<title>\w*):([^:]*{0}[^:]*):(?<ep>\w*)", hash);

regex will look like:

(?:4D|\?\?) (?:5A|\?\?) (?:02|\?\?) (?:68|\?\?) (?:6B|\?\?) (?:6A|\?\?)

每个部分匹配 2 个十六进制字符或 2 个 ?s。

看看regex demo

【讨论】:

  • 我在第一行收到了这个错误:
    'string.Join(string, string[])' 的最佳重载方法匹配有一些无效参数
    参数 2:无法从'System.Collections.Generic.IEnumerable' 到 'string[]'
  • 你添加using System.Linq;了吗?无论如何,您可以在Select 子句的末尾附加.ToArray() 以将IEnumerable&lt;string&gt; 转换为string[]
  • 我追加 .ToArray() 并解决错误,但该函数为所有模式返回 0!
  • 那么,什么是字符串,什么是模式?您确定您的模式与输入字符串匹配吗?也许它不应该匹配。
  • 当我在文件中只有哈希时,这项工作很好,例如:4D 00 68 02 6B 6A 68 6A 68 6B ?? 02 68 6A 00 02 FF 4D ?? 02 68 6B ?? 68,但我有其他值由“:”符号分隔
猜你喜欢
  • 1970-01-01
  • 2017-02-27
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 2016-12-03
相关资源
最近更新 更多