Using regular expressions when reading a file

Alexander Zhirov azhirov1991 at gmail.com
Thu May 5 17:53:57 UTC 2022


I want to use a configuration file with external settings. I'm 
trying to use regular expressions to read the `Property = Value` 
settings. I would like to do it all more beautifully. Is there 
any way to get rid of the line break character? How much does 
everything look "right"?

**settings.conf:**

```sh
host = 127.0.0.1
port = 5432
dbname = database
user = postgres
```

**code:**

```d
auto file = File("settings.conf", "r");
string[string] properties;
auto p_property = regex(r"^\w+ *= *.+", "s");
while (!file.eof())
{
   string line = file.readln();
   auto m = matchAll(line, p_property);
   if (!m.empty())
   {
     string property = matchAll(line, regex(r"^\w+", "m")).hit;
     string value = replaceAll(line, regex(r"^\w+ *= *", "m"), "");
     properties[property] = value;
   }
}
file.close();
writeln(properties);
```

**output:**

```sh
["host":"127.0.0.1\n", "dbname":"mydb\n", "user":"postgres", 
"port":"5432\n"]
```


More information about the Digitalmars-d-learn mailing list