gpt4 book ai didi

javascript - 通过不同的分隔符将两个不同格式的字符串分成几部分

转载 作者:行者123 更新时间:2023-12-03 01:37:57 25 4
gpt4 key购买 nike

有一个用户输入字符串,它可以有两种不同的格式,但有一些细微的变化:

Some AB, Author C, Names DEF,(2018) The title string. T journal name, 10, 560–564
Some AB, Author C, Names DEF (2018) The title string? T journal name 10:560-564
Some AB, Author C, Names DEF et al (2018) The title string? T journal name 10:560-564
Some AB, Author C, Names DEF. The title string. T journal name 2018; 10: 560-564
Some AB, Author C, Names DEF. The title string. T journal name 2018;10:560-564

我需要得到的是:

  1. 作者字符串部分:Some AB、Author C、Names DEFSome AB、Author C、Names DEF et al
  2. 文章标题字符串:标题字符串标题字符串?
  3. 期刊名称字符串:T 期刊名称
  4. 年份值:2018
  5. 版本值:10
  6. 页码560-564

所以我必须用分隔符 .(1234);: 分割字符串.

我没有有效的正则表达式,而且我不知道如何处理这两种格式,它们的年份值位于不同的位置。

我从以下内容开始:

string.split(/^\(\d+\)\s*/)

但是当我得到一个数组时,我该如何继续。

最佳答案

我还建议使用匹配模式:

^([^.(]+)(?:\((\d{4})\)|\.)\s*([^?!.]*.)\s*([^0-9,]+)(\d{4})?[,; ]*([^,: ]*)[,;: ]*(\d+(?:[–-]\d+)?)

或者更具可读性的版本 named capture groups *:

^(?<author>[^.(]+)(?:\((?<yearf1>\d{4})\)|\.)\s*(?<title>[^?!.]*.)\s*(?<journal>[^0-9,]+)(?<yearf2>\d{4})?[,; ]*(?<issue>[^,: ]*)[,;: ]*(?<pages>\d+(?:[–-]\d+)?)

我支持 Schifini 使用否定字符类来查找所需片段的方法。
为了区分这两种不同的格式,我为年份格式 1 和格式 2 添加了两个可选的命名组,并将其余部分包装在其他捕获组中。剩下的唯一事情就是检查第 2 组或第 5 组是否包含年份。

Demo

代码示例:

const regex = /^([^.(]+)(?:\((\d{4})\)|\.)\s*([^?!.]*.)\s*([^0-9,]+)(\d{4})?[,; ]*([^,: ]*)[,;: ]*(\d+(?:[–-]\d+)?)/gm;
const str = `Some AB, Author C, Names DEF,(2018) The title string. T journal name, 10, 560–564
Some AB, Author C, Names DEF (2018) The title string? T journal name 10:560-564
Some AB, Author C, Names DEF et al (2018) The title string? T journal name 10:560-564
Some AB, Author C, Names DEF. The title string. T journal name 2018; 10: 560-564
Some AB, Author C, Names DEF. The title string. T journal name 2018;10:560-564`;
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++;
}
array={};
m.forEach((match, groupIndex) => {
switch(groupIndex) {
case 0:
console.log(`Full match: ${match}`);
break;
case 1:
array['author'] = match.trim();
break;
case 2:
if(match)
array['year'] = match;
break;
case 3:
array['title'] = match.trim();
break;
case 4:
array['journal'] = match.trim();
break;
case 5:
if(match)
array['year'] = match.trim();
break;
case 6:
array['issue'] = match.trim();
break;
case 7:
array['pages'] = match.trim();
break;
default:
console.log(`Unknown match, group ${groupIndex}: ${match}`);
}
});
console.log(JSON.stringify(array));
}

*Javascript are not supported 中的命名捕获组在所有主要浏览器中。只需删除它们或使用 Steve Levithan's XRegExp library解决了这些问题。

关于javascript - 通过不同的分隔符将两个不同格式的字符串分成几部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50980925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com