[英]global Regexp is returning incorrect index inside for loop
我正在嘗試從字符串中刪除時間戳(格式為數字破折號)。 在這個過程中,我嘗試了全局 RegExp。 我想出了以下代碼:
for(let filename of ["123-123_aaa_bbb_ccc","aaa_bbb_ccc_129-999"])
{
let s=filename.split("_")
let globalRegex = new RegExp('^\d+\-\d+$', 'g');
for(let si of s){
if(globalRegex.test(si)) break
}
console.log(`match found at: `,globalRegex.lastIndex)
}
返回:
match found at: 0
match found at: 0
我的問題是:
這里有很多問題:
0
是因為您的正則表達式不匹配,並且它不匹配是因為您在常規字符串文字中定義了正則表達式字符串,因此丟失了所有單個反斜杠。 模式必須使用正則表達式文字設置, let globalRegex = /^\d+\-\d+$/;
(請參閱為什么這個 javascript 正則表達式不起作用? )。 請注意沒有g
標志,如果將其與RegExp#test()
一起使用,則不得使用g
標志以避免出現問題(請參閱為什么帶有全局標志的 RegExp 會給出錯誤的結果? )。0
作為輸出,因為/^\d+\-\d+$/
正則表達式可以並且只會在字符串的開頭匹配(索引=0)。 您似乎想要獲取字符串中“單詞”或“令牌”的 ID,因此您需要對它們進行計數。因此,您可以將代碼重寫為
for(let filename of ["123-123_aaa_bbb_ccc","aaa_bbb_ccc_129-999"]) { let result = -1; let s=filename.split("_") let globalRegex = /^\d+\-\d+$/; for (const [index, si] of s.entries()) { if(globalRegex.test(si)) { result = index break } } console.log(`match found at: `, result) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.