匹配十六进制符号字节正则表达式
Match hexadecimal notated bytes regex
我正在尝试使用正则表达式匹配和分组十六进制字节(即 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?
我会使用四个独立的捕获组:
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
抱歉这么说,但是 haxe EReg class 遗漏了一些常见用例的方法。然而,它仍然是可以实现的。试试这个:
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;
}
}
}
我正在尝试使用正则表达式匹配和分组十六进制字节(即 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?
我会使用四个独立的捕获组:
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
抱歉这么说,但是 haxe EReg class 遗漏了一些常见用例的方法。然而,它仍然是可以实现的。试试这个:
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;
}
}
}