I'm pretty stumped as to what's wrong with the following regular expression:

var // this regex digests a string into leading whitespace,
    // content text, and trailing whitespace.
    lineRegex = /^(\s*)(\S.*\S|\S)?(\s*)$/g,
    /* ... */;

lineRegex is supposed to match anything. There is not even one required character, and if there are characters in the string, they are all either white space or not white space. When I paste the exact regex into FireBug console and add .exec(""), I get the expected result, ["", "", undefined, ""]. But in my JSFiddle (http://jsfiddle.net/Lay9k/9/) I have:

try {
    var sections = lineRegex.exec(lineTxt),
        rawLeadingWs = sections[1] || "",
        contentText = sections[2] || "",
        importantTabs = rawLeadingWs.replace(
            oneTabWorthOfSpaces, "\t"
        ),
        tabsAndAligningSpaces =
            aligningTabRegex.exec(importantTabs),
        // I don't like this as much as Lint does.
        importantWsLength = 
            (tabsAndAligningSpaces[1] || "").replace(/[^\t]/g, "")
            .length * spacesPerTab +
            (tabsAndAligningSpaces[2] || "").length;
} catch (wtf) {
    console.log({
        lineText: lineTxt,
        sections: sections,
        rawLeadingWs: rawLeadingWs,
        contentText: contentText,
        importantTabs: importantTabs,
        tabsAndAligningSpaces: tabsAndAligningSpaces,
        importantWsLength: importantWsLength
    });
    throw wtf;
}

and I get sections is null when lineTxt is "". So what gives?

有帮助吗?

解决方案

I think the problem is that the lastIndex property of the regex is not reset properly.

Here's a related issue: Why does Javascript's regex.exec() not always return the same value?

reg.lastIndex = 0; from one of the answers seems to fix it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top