我正在使用 XRegexP 专门解析文本文件以查找两组预定义注释标签之间的内容,我无法更改这些标签,因此我需要找到一种方法使其与提供的文本一起使用。
我使用提供的正则表达式找到了所有标签的列表(链接中的示例还包括示例内容):https ://regex101.com/r/kCwyok/1/
然后,我使用 XRegexP 的matchRecursive
函数来获取开始和结束标记之间的所有内容,这些内容几乎都可以正常工作。
// Map the list of component tags and extract data from them
return generateComponentList(data).map((component) => {
console.log(chalk.blue('Processing', component[1], 'component.'))
const contents = XRegExp.matchRecursive(data, '<!-- @\\[' + component[1] + '\\][.\\w-_+]* -->', '<!-- @\\[/' + component[1] + '\\] -->', 'g')
let body = ''
let classes = ''
contents.map((content) => {
const filteredContent = filterContent(content)
body = filteredContent.value
classes = cleanClasses(component[2])
console.log(chalk.green(component[1], 'processing complete.'))
})
// Output the content as a JSON object
return {
componentName: component[1],
classes,
body
}
})
我遇到的问题是CodeExample
标签存在两次,标签相同但内容不同,但是,因为matchRecursive
似乎没有回调函数,它只是同时在该组件的所有实例上运行匹配所以CodeExample
返回所有内容的1 个或 10 个实例都没有关系。
有没有办法我可以实际添加某种回调到 matchRecursive?如果做不到这一点,有没有办法让 JavaScript 了解正在查看哪个 CodeExample 实例,以便我可以直接引用数组位置?我认为 XRegexP 知道它正在查看哪个数字 CodeExample 标记,那么有没有办法捕获它?
为了清楚起见,这是完整的代码:https ://pastebin.com/2MpdvdNA
我想要的所需输出是包含以下数据的 JSON 文件:
[
{
componentName: "hero",
classes: "",
body: "# Creating new contexts"
},
{
componentName: "CodeExample",
classes: "",
body: "## Usage example
```javascript
Import { ICON_NAME } from 'Icons'
```"
},
{
componentName: "ArticleSection",
classes: "",
body: // This section is massive and not relevant to question so skipping
},
{
componentName: "NoteBlock",
classes: ["warning"],
body: "> #### Be Careful
> Eu laboris eiusmod ut exercitation minim laboris ipsum magna consectetur est [commodo](/nope)."
},
{
componentName: "CodeExample",
classes: "",
body: "#### Code example
```javascript
class ScrollingList extends React.Component {
constructor(props) {
super(props);
this.listRef = React.createRef();
}
render() {
return (
<div ref={this.listRef}>{/* ...contents... */}</div>
);
}
}
```"
}
// Skipping the rest as not relevant to question
]
抱歉,如果我没有清楚地解释这一点,我已经看这个太久了。