我对以下正则表达式的错误感到非常难过:
var // this regex digests a string into leading whitespace,
// content text, and trailing whitespace.
lineRegex = /^(\s*)(\S.*\S|\S)?(\s*)$/g,
/* ... */;
lineRegex
应匹配任何。甚至没有一个必需的字符,如果字符串中有字符,则它们都是空格或不是空格。当我将完全正则表达式粘贴到FireBug控制台并添加.exec("")
时,我得到了预期的结果["", "", undefined, ""]
。但在我的JSFiddle(http://jsfiddle.net/Lay9k/9/)中我有:
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;
}
当sections is null
为lineTxt
时,我得到""
。那是什么给出了什么?
答案 0 :(得分:0)
我认为问题在于正则表达式的lastIndex
属性未正确重置。
以下是相关问题:Why does Javascript's regex.exec() not always return the same value?
来自其中一个答案的 reg.lastIndex = 0;
似乎解决了这个问题。