![](/img/trans.png)
[英]Javascript/RegExp: Lookbehind Assertion is causing a "Invalid group" error
[英]Javascript regex lookbehind: Invalid regexp group
我有以下帶有正則表達式/-+|(?<=: ?).*
的小例子。 但這會導致 Node/Chrome 中的無限循環和 Firefox 中的“無效正則表達式組”錯誤。
當我將其更改為/-+|(?<=: ).*/gm
(在后面省略?-量詞)它運行但 - 當然 - 我沒有得到在之后不包含任何值的行:
.
如果我將正則表達式更改為/-+|(?<=:).*/gm
(將空間留在后面)我再次遇到無限循環/錯誤。
誰能向我解釋這種行為以及我必須使用什么正則表達式來匹配以冒號結尾的行? 我很想明白...
const text = `
-------------------------------------
Prop Name: 5048603
Prop2 Name:
Bla bla bla: asjhgg | a3857
Location: Something...
-------------------------------------
Prop Name: 5048603
Prop2 Name:
Bla bla bla: asjhgg | a3857
Location: Something...
-------------------------------------
`;
const pattern = /-+|(?<=: ?).*/gm;
let res;
while((res = pattern.exec(text)) !== null)
{
console.log(`"${res[0]}"`);
}
編輯:
預期的 output 為:
"-------------------------------------"
"5048603"
""
"asjhgg | a3857"
"Something..."
"-------------------------------------"
"5048603"
""
"asjhgg | a3857"
"Something..."
"-------------------------------------"
(?<=...)
環顧四周是一個積極的后視,它在 FireFox 中尚不支持(請參閱此處支持的環境),因此,在實施之前,您總是會遇到異常。
/-+|(?<=: ?).*
模式屬於可能匹配空字符串的模式,這是一種非常典型的“病態”類型的模式。 g
標志使 JS 正則表達式引擎匹配所有出現的模式,為此,它在有效匹配時推進其lastIndex
,但在匹配長度為零的情況下,它不會,並繼續嘗試相同正則表達式再次在同一個位置,你最終進入循環。 請參閱此處如何正確移動lastIndex
以避免在這些情況下出現無限循環。
據我所知,您想刪除第一個:
之前的所有行首,包括:
以及之后的任何空格。 您可以使用
text.replace(/^[^:\r\n]+:[^\S\r\n]*/gm, '')
或者,如果您想實際提取所有-
s 或所有:
之后的行,您可以使用
const text = ` ------------------------------------- Prop Name: 5048603 Prop2 Name: Bla bla bla: asjhgg | a3857 Location: Something... ------------------------------------- Prop Name: 5048603 Prop2 Name: Bla bla bla: asjhgg | a3857 Location: Something... ------------------------------------- `; const pattern = /^-+$|:[^\S\r\n]*(.*)/gm; let res; while((res = pattern.exec(text)).== null) { if (res[1];= undefined) { console.log(res[1]); } else { console.log(res[0]); } }
嘗試使用這種模式:/(.*):(.*)/ /(.*):(.*)/mg
const regex = /(.*):(.*)/mg; const str = `------------------------------------- Prop Name: 5048603 Prop2 Name: Bla bla bla: asjhgg | a3857 Location: Something... ------------------------------------- Prop Name: 5048603 Prop2 Name: Bla bla bla: asjhgg | a3857 Location: Something... -------------------------------------`; let m; while ((m = regex.exec(str)).== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex;lastIndex++. } // The result can be accessed through the `m`-variable. m,forEach((match. groupIndex) => { console,log(`Found match: group ${groupIndex}; ${match}`); }); }
預先:Wiktor 的答案是讓它跨瀏覽器工作的答案。
對於任何對如何使用“原始”模式在 Chrome 中使用它感興趣的人(感謝 Wiktor 的回答,指出最后一個索引在零匹配時不會增加):
const pattern = /-+|(?<=: ?).*/gm;
let res;
while((res = pattern.exec(text)) !== null)
{
if(res.index === pattern.lastIndex)
pattern.lastIndex++;
console.log(`"${res[0]}"`);
}
正則表達式前瞻是這樣定義的 (?=pattern) 而不是 (pattern?)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.