我正在尝试在 nodejs
的帮助下获取文件内容fs.readFileSync()
像这样将函数转换为字符串:
let fileData = fs.readFileSync('./path, 'utf8');
之后我想通过 regex
获取两个字符串之间的内容:
我有一个类似这样的字符串:
<route-meta>
{
"requiresAuth": true
}
</route-meta>
<template>
</template>
<script>
export default {
name: "check"
}
</script>
<style scoped>
</style>
我需要在 <route-meta>
之间查找文本/字符串和</route-meta>
所以结果应该是:
{
"requiresAuth": true
}
我尝试使用 fileData.match(/<route-meta>(.*?)<\/route-meta>/);
执行此操作但不知怎的,它给了我 null
结果
我按照这个例子进行操作:Regex match text between tags
我还尝试检查 fileData.replace('route-meta', '');
但它仍然没有给我想要的结果,我的意思是我无法使用 fileData
进行任何字符串操作.
指导我哪里做错了。
最佳答案
请不要使用正则表达式进行 XML 解析
但是要回答你的问题,你可以尝试这个
let re = /<route-meta>[\s\S]*?<\/route-meta>/
let re1 = /<(\/*)route-meta>/gi
let newstr = fileData.match(re)[0].replace(re1,"")
console.log(newstr)
re
使用 match
查找包含内容的全套标签
re1
使用 replace
删除开始和结束标记
关于javascript - Nodejs readFileSync 两个字符串之间的正则表达式标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61243033/