全局正则表达式在 for 循环中返回不正确的索引
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)
}
哪个returns:
match found at: 0
match found at: 0
我的问题是:
- 如何正确地从字符串中删除时间戳?
- 为什么 运行 的正则表达式都返回 0?
- 我预计(返回 0 然后 3 索引)看起来像状态
全局正则表达式的一部分没有为第二个 运行 重新初始化。
但是我认为它会是,因为它在 for 中重新声明
循环
这里有不少问题:
- 你得到
0
s 是因为你的正则表达式不匹配,它不匹配是因为你在常规字符串文字中定义了正则表达式字符串,因此丢失了所有单个反斜杠。该模式必须使用正则表达式 let globalRegex = /^\d+\-\d+$/;
(参见 Why this javascript regex doesn't work?). Note the absence of the g
flag, if you use it with RegExp#test()
, you must not use g
flag to avoid issues (see Why does a RegExp with global flag give wrong results?)进行设置。
- 即使您正确定义了正则表达式,您也会得到
0
s 作为输出,因为 /^\d+\-\d+$/
正则表达式可以并且只会匹配字符串的开头(索引=0)。你好像想得到字符串中“words”或“tokens”的ID,所以你需要统计一下。
因此,您可以re-write将代码设为
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)
}
我正在尝试从字符串中删除时间戳(格式为数字破折号)。在此过程中,我尝试了全局 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)
}
哪个returns:
match found at: 0
match found at: 0
我的问题是:
- 如何正确地从字符串中删除时间戳?
- 为什么 运行 的正则表达式都返回 0?
- 我预计(返回 0 然后 3 索引)看起来像状态 全局正则表达式的一部分没有为第二个 运行 重新初始化。 但是我认为它会是,因为它在 for 中重新声明 循环
这里有不少问题:
- 你得到
0
s 是因为你的正则表达式不匹配,它不匹配是因为你在常规字符串文字中定义了正则表达式字符串,因此丢失了所有单个反斜杠。该模式必须使用正则表达式let globalRegex = /^\d+\-\d+$/;
(参见 Why this javascript regex doesn't work?). Note the absence of theg
flag, if you use it withRegExp#test()
, you must not useg
flag to avoid issues (see Why does a RegExp with global flag give wrong results?)进行设置。 - 即使您正确定义了正则表达式,您也会得到
0
s 作为输出,因为/^\d+\-\d+$/
正则表达式可以并且只会匹配字符串的开头(索引=0)。你好像想得到字符串中“words”或“tokens”的ID,所以你需要统计一下。
因此,您可以re-write将代码设为
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)
}