Using regex to potentially improve performance of string parsing?
<p>I have a string like this:</p>

<pre><code>// string1
horse|cow|goat|zebra|
</code></pre>

<p>and another string like this:</p>

<pre><code>// string2
horse:a,pig:b,cow:z,monkey:g,goat:a,
</code></pre>

<p>my goal is to split string1, then pick out any occurrences of it in string2, to build a histogram. I am currently doing this:</p>

<pre><code>var histogram = {};

var animals = string1.split("|");
for (var i = 0; i &lt; animals.length; i++) {
    var animal = animals[i];
    var animalColon = animal + ":";

    var index = string2.indexOf(animalColon);
    while (index != -1) {
        var indexColon = index + animalColon.length;
        var indexFinal = string2.indexOf(",", indexColon);
        var letter = string2.substring(indexColon, indexFinal);

        if (histogram[letter] == null) {
            histogram[letter] = 1;
        }
        else {
            histogram[letter] = histogram[letter] + 1;
        }
        index = string2.indexOf(animalColon, index + 1);
    }
}
</code></pre>

<p>at the end, it might print something like:</p>

<pre><code>// histogram:
a: 2 instances // from { horse, goat }
z: 1 instance  // from { cow }
</code></pre>

<p>the above will work, but I have to dp <em>animals.length</em> passes through string2 to check everyone.</p>

<p>Is there a way to use regular expressions to do this parsing - essentially run all tests in parallel, instead of doing multiple passes through? Since string2 is const, it seems that all checks could be done simultaneously (not sure if regexes are implemented like this).</p>

<p>I increased the number of elements in string1 and string2 on the order of thousands of elements and it still runs quite fast, but am worried about slower machines, maintainability, and stuff like that,</p>

<p>Thanks</p>
