【问题标题】:Nodejs readFileSync regex tag between two strings两个字符串之间的Nodejs readFileSync正则表达式标记
【发布时间】:2020-07-29 06:24:36
【问题描述】:

我正在尝试借助 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>

我需要在&lt;route-meta&gt;&lt;/route-meta&gt; 之间找到文本/字符串,这样结果应该是:

{
   "requiresAuth": true
}

我尝试使用fileData.match(/&lt;route-meta&gt;(.*?)&lt;\/route-meta&gt;/); 执行此操作,但不知何故它给了我null 结果

我遵循了这个例子:Regex match text between tags

我还尝试检查fileData.replace('route-meta', '');,但它仍然没有给我想要的结果我的意思是我无法使用fileData 进行任何字符串操作。

指导我哪里出错了。

【问题讨论】:

  • @PatrickRoberts Hey Patrick 我正在执行fs.readFileSync() 来获取文件数据到字符串中,这仍然是你提到的问题吗?

标签: javascript node.js regex fs string-matching


【解决方案1】:

请不要使用正则表达式进行 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 删除开始和结束标签

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多