我有这个字符串,我想知道如何提取“10-K_20190304_29_1_20190515”部分。
"nCABALLERO MARIA\r\n10.1-K\r\n10-K_20190304_29_1_20190515\r\n6204 DEPORTES SANTIAGO - PEÑALOLÉN"
我试过这个,.+(?<=_).+但它给我带来了更多我需要的角色。
我该如何解决这个问题?
我有这个字符串,我想知道如何提取“10-K_20190304_29_1_20190515”部分。
"nCABALLERO MARIA\r\n10.1-K\r\n10-K_20190304_29_1_20190515\r\n6204 DEPORTES SANTIAGO - PEÑALOLÉN"
我试过这个,.+(?<=_).+但它给我带来了更多我需要的角色。
我该如何解决这个问题?
在这里,我们喜欢从一个简单的左右边界开始,收集我们想要的数据并将其保存在一个捕获组($1)中。让我们从:
[0-9]{2}-.+[0-9]{8}
让我们添加我们的捕获组:
([0-9]{2}-.+[0-9]{8})
const regex = /[0-9]{2}-.+[0-9]{8}/gm;
const str = `nCABALLERO MARIA\\r\\n10.1-K\\r\\n10-K_20190304_29_1_20190515\\r\\n6204 DEPORTES SANTIAGO - PEÑALOLÉN`;
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}`);
});
}
如果不需要此表达式,可以在regex101.com中对其进行修改或更改。
jex.im可视化正则表达式:
如果我们希望添加更多边界,我们当然可以这样做,这取决于我们可能的输入可能是什么样子。例如,这个表达式有更多的边界:
([0-9]{2}-[A-Z]+_[0-9]{8}[0-9_]+.+?[0-9]{8})
const regex = /([0-9]{2}-[A-Z]+_[0-9]{8}[0-9_]+.+?[0-9]{8})/gm;
const str = `nCABALLERO MARIA\\r\\n10.1-K\\r\\n10-K_20190304_29_1_20190515\\r\\n6204 DEPORTES SANTIAGO - PEÑALOLÉN`;
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}`);
});
}