We don't need to track and check lengthSource, especially in this first loop.
Just use "while (boost::starts_with(source, match)) {"

For the second loop, "while (boost::ends_with(source, match)) {" is probably also good enough.