[英]JS RegExp matches in FireBug… but not JSFiddle?
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 . lineRegex
应该匹配任何东西 。 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, ""]
. 当我将确切的正则表达式粘贴到FireBug控制台中并添加
.exec("")
,得到了预期的结果["", "", undefined, ""]
。 But in my JSFiddle ( http://jsfiddle.net/Lay9k/9/ ) I have: 但是在我的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;
}
and I get sections is null
when lineTxt
is ""
. 当
lineTxt
为""
时,我得到的sections is null
。 So what gives? 那有什么呢?
I think the problem is that the lastIndex
property of the regex is not reset properly. 我认为问题在于正则表达式的
lastIndex
属性未正确重置。
Here's a related issue: Why does Javascript's regex.exec() not always return the same value? 这是一个相关的问题: 为什么Javascript的regex.exec()并不总是返回相同的值?
reg.lastIndex = 0;
from one of the answers seems to fix it. 答案之一似乎可以解决它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.