Sam Saint-Pettersen
Sam Saint-Pettersen

Reputation: 511

Match hexadecimal notated bytes regex

I am trying to match and group hexadecimal bytes (i.e. 2 digit hex values) with the regular expression -> ~/([0-9a-f]{2}/.

I want to store these grouped matches without altering the original string sbytes.

What do I need to do to achieve this? Thanks.

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?

Upvotes: 1

Views: 476

Answers (2)

stroncium
stroncium

Reputation: 1430

Sorry to say that, but haxe EReg class misses some methods for frequent usecases. However, it's still achievable. Try this:

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;
    }
  }
}

Upvotes: 3

hek2mgl
hek2mgl

Reputation: 158060

I would use four separate capturing groups:

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));
    }
}

You can try the code here: http://try.haxe.org/#CA3d8

Upvotes: 2

Related Questions