【问题标题】:Get specific content in svg file with js用js获取svg文件中的特定内容
【发布时间】:2021-06-04 07:59:44
【问题描述】:

我需要在我的 svg 文件中检索类似“{ content }”的特定内容

所以我想我需要使用正则表达式,但我不知道该怎么做

test.svg

<svg width="500" height="100">
    <text x="47.872" y="11.064" id="smartCar">{garage/temp} °C</text>
    <circle id="circle1" cx="20" cy="20" r="10"
            style="stroke: none; fill: #ff0000;"/>
    <text x="47.872" y="11.064" id="smartCar">{home/sensors/temp/kitchen} °C</text>
</svg>

findContent.js

    var fs = require('fs');

const fileContent = fs.readFileSync( "test.svg","UTF-8");
const lines = fileContent.split("\n");
console.log(lines);
lines.forEach((line) => {
    const topicMatch = line.match();  //need regex
            if (topicMatch) {
                console.log(topicMatch[1]) // display all content with syntax {content}
            }
})

预期结果:

  • {车库/温度}
  • {home/sensors/temp/kitchen}

【问题讨论】:

标签: javascript regex svg


【解决方案1】:

试试这个:

/\{[\w\/]+\}/g

你可以测试一下here

【讨论】:

    【解决方案2】:

    使用

    const regex = /{[^{}]+}/g
    
    const string = `<svg width="500" height="100">
        <text x="47.872" y="11.064" id="smartCar">{garage/temp} °C</text>
        <circle id="circle1" cx="20" cy="20" r="10"
                style="stroke: none; fill: #ff0000;"/>
        <text x="47.872" y="11.064" id="smartCar">{home/sensors/temp/kitchen} °C</text>
    </svg>`
    
    console.log(string.match(regex))

    regex proof

    解释

    --------------------------------------------------------------------------------
      {                        '{'
    --------------------------------------------------------------------------------
      [^{}]+                   any character except: '{', '}' (1 or more
                               times (matching the most amount possible))
    --------------------------------------------------------------------------------
      }                        '}'
    

    【讨论】:

      猜你喜欢
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 2019-10-16
      • 2021-04-04
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多