DEV Community

Jesse Phillips
Jesse Phillips

Posted on

4 3

Parsing a String in D

Parsing a String

First thing is first we want to read in a file. I won't be writing full compiling examples as I'm usually doing this on my phone. However, in general any examples can be pasted directly into a main function because D has nested everything.

void main() {
   import std.file;
   auto data = readText("filename.ext");
}
Enter fullscreen mode Exit fullscreen mode

readText reads the entire file into memory. Usually not a bad start but could be a problem with very large files. D also utilizes immutable strings, so techniques I'm showing generally do not use additional memory.

Matching Beginning or End

startsWith

Sometimes all that is needed is a check if the beginning or end matches a value.

import std.algorithm;
auto data = "word word"
assert(data.startsWith("word"));
assert(data.endsWith("word"));
assert(data.skipOver("word"));
assert(data == " word");
Enter fullscreen mode Exit fullscreen mode

skipOver will not only identify if the string is found at the beginning, but also move data past the string.

Removing Whitespace

strip

import std.string;
auto data = " str ";
assert(data.strip == "str");
assert(data.stripLeft == " str");
assert(data.stripRight == "str ");
Enter fullscreen mode Exit fullscreen mode

Along with whitespace an argument can be past in to specify a specific string to strip off.

Find a String

find

Rather than reiterate here, see my previous post. I also am preparing the next post which dives into more of the variations.

Regular Expressions

The standard regex library is very nice. I won't be going over examples because regular expressions themselves are a more advanced topic.

https://dlang.org/phobos/std_regex.html

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More