匹配十六进制标记的字节正则表达式

时间:2015-01-22 16:22:25

标签: regex haxe

我正在尝试匹配并将十六进制字节(即2位十六进制值)与正则表达式分组 - > ~/([0-9a-f]{2}/

我想存储这些分组的匹配而不改变原始字符串sbytes

我需要做些什么才能实现这一目标?感谢。

var sbytes: String = "cafebabe";
var hexr = ~/([0-9a-f]{2})/; // Match a hexadecimal notated byte.
hexr.match(sbytes);
trace(hexr.matched(1));

// I want to match each byte (ca, fe, ba, be) into a match group
// (E.g. ca = hexr.matched(1), fe = hexr.matched(2), et cetera).
// How do I do this?

2 个答案:

答案 0 :(得分:3)

很抱歉这样说,但haxe EReg类错过了一些频繁使用的方​​法。但是,它仍然可以实现。试试这个:

class Test {
  static function main() {
    var sbytes: String = "cafebabe";

    var hexbyteRe = ~/[0-9a-f]{2}/;

    var pos = 0;
    while(hexbyteRe.matchSub(sbytes, pos)){
      trace(hexbyteRe.matched(0));
      var mp = hexbyteRe.matchedPos();
      pos = mp.pos + mp.len;
    }
  }
}

答案 1 :(得分:2)

我会使用四个独立的捕获组:

class Test {

    static function main() {
        var sbytes: String = "cafebabe";
        // Match 4 hexadecimal notated bytes. Match each of them in a 
        // separate capturing group.
        var hexr = ~/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/;
        hexr.match(sbytes);

        trace(hexr.matched(1));
        trace(hexr.matched(2));
        trace(hexr.matched(3));
        trace(hexr.matched(4));
    }
}

您可以在此处尝试代码:http://try.haxe.org/#CA3d8