Skip to content

Instantly share code, notes, and snippets.

@YellowAfterlife
Last active July 4, 2020 08:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save YellowAfterlife/9643940 to your computer and use it in GitHub Desktop.
Save YellowAfterlife/9643940 to your computer and use it in GitHub Desktop.
Simplistic .properties parser
class Main {
static function parseProperties(text:String):Map<String, String> {
var map:Map<String, String> = new Map(),
ofs:Int = 0,
len:Int = text.length,
i:Int, j:Int,
endl:Int;
while (ofs < len) {
// find line end offset:
endl = text.indexOf("\n", ofs);
if (endl < 0) endl = len; // last line
// do not process comment lines:
i = text.charCodeAt(ofs);
if (i != "#".code && i != "!".code) {
// find key-value delimiter:
i = text.indexOf("=", ofs);
j = text.indexOf(":", ofs);
if (j != -1 && (i == -1 || j < i)) i = j;
//
if (i >= ofs && i < endl) {
// key-value pair "key: value\n"
map.set(StringTools.trim(text.substring(ofs, i)),
StringTools.trim(text.substring(i + 1, endl)));
} else {
// value-less declaration "key\n"
map.set(StringTools.trim(text.substring(ofs, endl)), "");
}
}
// move on to next line:
ofs = endl + 1;
}
return map;
}
static function main() {
var src = "value1: some text\n"
+ "#value2 = test\n"
+ "value3 = score : {num}",
out = parseProperties(src);
trace(src);
trace(out);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment