我需要按第x章来划分,x可以是阿拉伯数字或者中文数字
时间: 2023-08-31 17:34:13 浏览: 45
好的,按照您的要求来修改之前的代码,可以使用正则表达式来匹配章节标题中的数字,以得到每一章的序号。以下是修改后的代码:
```
function splitChapters(novelData) {
const pattern = /^\s*第[一二三四五六七八九十\d]+[章节]\s+/; // 匹配 "第X章" 开头的段落
const matches = novelData.match(new RegExp(pattern.source, 'g')); // 使用全局匹配模式,匹配所有章节标题
if (!matches) {
console.error('无法在小说文本中匹配到章节标题');
return [];
}
const chapters = [];
let chapterStartIndex = 0;
for (let i = 0; i < matches.length; i++) {
const title = matches[i];
const titleIndex = novelData.indexOf(title, chapterStartIndex); // 从上一个章节的结束位置开始搜索章节标题
if (titleIndex < chapterStartIndex) {
console.error(`无法在小说文本中匹配到第${i+1}章的标题`);
return [];
}
const content = novelData.slice(chapterStartIndex, titleIndex).trim();
const chapterNumber = title.match(/[一二三四五六七八九十\d]+/)[0]; // 从章节标题中匹配出章节序号
chapters.push({ index: parseInt(chapterNumber), title, content });
chapterStartIndex = titleIndex;
}
chapters.push({ // 处理最后一章的内容
index: chapters.length + 1,
title: '',
content: novelData.slice(chapterStartIndex).trim(),
});
return chapters;
}
```
修改说明:
1. 在章节标题匹配正则表达式中,允许匹配中文数字。
2. 在处理每一章的时候,匹配章节标题中的数字,以得到每一章的序号。
希望这个修改后的方法能够满足您的需求。
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)