load data from txt file
Tony
tonytdominguez at aol.com
Thu Jan 4 08:39:04 UTC 2018
On Thursday, 4 January 2018 at 05:52:35 UTC, codephantom wrote:
> On Wednesday, 3 January 2018 at 05:45:32 UTC, Tony wrote:
>>
>> Someone else should know what the correct replacement
>> is for removechars().
>>
>
> the replacement is known as 'programming' ;-)
>
> //string trimmed = removechars!string(line,"[\\[\\]\"\n\r]");
> string trimmed;
> foreach(c; line)
> {
> if(c != '[' && c != ']' && c != '\"' && c != '\r' && c !=
> '\n' )
> trimmed ~= c;
> }
OK, thanks. The removechars() note about deprecation said to use
std.regex instead so I have been looking at that and after a
struggle did make some use of std.regex.replaceAll. Reminded me
of the famous Jamie Zawinski quote: "Some people, when confronted
with a problem, think "I know, I'll use regular expressions." Now
they have two problems.
import std.stdio;
import std.string;
import std.algorithm;
import std.regex;
import std.file;
import std.format : format;
void checkLine(string line,long line_number)
{
// not expecting any whitespace or extra colons. Each line:
// ["key":"value"]
long colon_pos = std.string.indexOf(line,':');
assert(colon_pos != -1,format("ERROR: no colon on line
%s",line_number));
long splitter_string_pos = std.string.indexOf(line,"\":\"");
assert(splitter_string_pos != -1,
format("ERROR: line %s missing quote(s) adjacent to
:",line_number));
assert(line[0..2] == "[\"",format("ERROR: no [\" at line %s
start",line_number));
assert(line[line.length - 2 .. line.length] == "\"]",
format("ERROR: no \"] at end of line %s",line_number));
}
void main()
{
string[string] data;
string filename = "users.txt";
assert( std.file.exists(filename), format("ERROR: file %s not
found",filename));
auto f = std.stdio.File("users.txt","r");
scope(exit) { f.close(); }
string line = f.readln!();
long line_number = 0;
while ( line !is null)
{
import std.uni : lineSep;
line_number++;
checkLine(std.string.chomp!(string)(line),line_number);
auto fields = std.algorithm.findSplit(line,"\":\"");
string key =
std.regex.replaceAll(fields[0],regex(`^\["(.*)$`),"$1");
string value =
std.regex.replaceAll(fields[2],regex(`^(.*)"\]\r?\n$`),"$1");
data[key] = value;
line = f.readln!();
}
writeln(data);
writeln("value for key admin:",data["admin"]);
writeln("value for key test:",data["test"]);
}
More information about the Digitalmars-d
mailing list