[英]JS RegExp matches in FireBug… but not JSFiddle?
我很困惑下面的正则表达式出了什么问题:
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;
}
当lineTxt
为""
时,我得到的sections is null
。 那有什么呢?
我认为问题在于正则表达式的lastIndex
属性未正确重置。
这是一个相关的问题: 为什么Javascript的regex.exec()并不总是返回相同的值?
reg.lastIndex = 0;
答案之一似乎可以解决它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.