内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我有这个字符串,我想知道如何提取“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”部分。
text.Split({“\r\n”},StringSplitOptions.None)(2)
在这里,我们想从一个简单的左右边界开始,收集我们的欲望数据并将其保存在捕获组($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}`);
});
}