Using regular expressions when reading a file
Ali Çehreli
acehreli at yahoo.com
Thu May 5 19:19:26 UTC 2022
On 5/5/22 12:05, Alexander Zhirov wrote:
> On Thursday, 5 May 2022 at 18:58:41 UTC, H. S. Teoh wrote:
>> You don't have to. Just add a `$` to the end of your regex, and it
>> should match the newline. If you put it outside the capture
>> parentheses, it will not be included in the value.
>
> In fact, it turned out to be much easier. It was just necessary to use
> the `m` flag instead of the `s` flag:
>
> ```d
> auto p_property = regex(r"^(\w+) *= *(.+)", "m");
> ```
>
Couldn't help myself from improving. :) The following regex works in my
Linux console. No issues with '\n'. (?) It also allows for leading and
trailing spaces:
import std.regex;
import std.stdio;
import std.algorithm;
import std.array;
import std.typecons;
import std.functional;
void main() {
auto p_property = regex(r"^ *(\w+) *= *(\w+) *$");
const properties = File("settings.conf")
.byLineCopy
.map!(line => matchFirst(line, p_property))
.filter!(not!empty) // OR: .filter!(m => !m.empty)
.map!(m => tuple(m[1], m[2]))
.assocArray;
writeln(properties);
}
Ali
More information about the Digitalmars-d-learn
mailing list