我正在嘗試在 Typescript 的特定位置進行正則運算式匹配。
這是我嘗試過的。
var str = "0123ABC789"
function matchesAt(rgx: RegExp, s : string, i : number) : string | void {
rgx.lastIndex = i
console.log(rgx.exec(s));
}
matchesAt(/(ABC)/g, str, 4 )
本質上,我正在嘗試重新創建 String.startsWith(string, number) 方法,但里面有一個正則運算式 - 而不是另一個字串。
我期望該函式僅在索引為 4 時才匹配。任何其他數字都應回傳 nil。
uj5u.com熱心網友回復:
您可以檢查匹配的字串長度加 i 是否等于以下 lastIndex:
function matchesAt(rgx: RegExp, s : string, i : number) : string | void {
rgx.lastIndex = i
let isMatching = rgx.exec(s);
if (isMatching && isMatching?.length > 1 && rgx.lastIndex - isMatching[1]?.length == i)
return s;
return void null;
}
uj5u.com熱心網友回復:
您可以使用粘性標志y:
該
y標志表示正則運算式僅嘗試從lastIndex屬性指示的索引匹配目標字串(與全域正則運算式不同,它不嘗試從任何后續索引匹配)。
function matchesAt(rgx, s, i) {
rgx.lastIndex = i;
return rgx.test(s); // use .test to get boolean result
}
var str = "0123ABC789";
console.log(matchesAt(/ABC/gy, str, 4)); // true
console.log(matchesAt(/ABC/gy, str, 3)); // false!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530723.html
