regex 带有全局搜索和替换捕获的多行正则表达式

jdg4fx2g  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(91)

我正在尝试替换这种格式的代码

{{>
    default-hero
    color="red"
    title="Foo"
    subheading="Bar"
    background="about-us-hero-desktop.jpg"
    squarePartial="company/square.hbs"
    squareBaseline=true
}}

字符串
用这个

{% set color = "red" %}
{% set heroTitle = "Foo" %}
{% set subheading = "Bar" %}
{% set background = "about-us-hero-desktop.jpg" %}
{% set squarePartial = "company/square.njk" %}
{% set squareBaseline = true %}

{% include "default-hero.njk" %}


这将对许多文件递归运行。这可能吗?我开始写这样的代码

oldContent = newContent;
  regex = /\{\{>\s*([a-zA-Z0-9-_/]+)?\s*([a-zA-Z0-9-_/\.=:"'\s]+)\s*\}\}/gi;
  replaceVal = '{% include $1.njk $2 %}';
  newContent = oldContent.replace(regex, replaceVal);


但它只是部分有效。

h22fl7wq

h22fl7wq1#

**不确定这是否可以完全从Regex实现。据我所知,在某种程度上,你需要JavaScript中的字符串replace

参考下面的代码:

function transformTemplate(input) {

  input = input.replace(/\n\s+/g, ''); // sanitizing for new lines and space

  
  let color = input.match(/color="(.*?)"/)[1]; // regex to capture color
  let title = input.match(/title="(.*?)"/)[1]; // regex to match Title
  let subheading = input.match(/subheading="(.*?)"/)[1]; // regex to match subheading
  let background = input.match(/background="(.*?)"/)[1]; // regex to match background
  let squarePartial = input.match(/squarePartial="(.*?)"/)[1]; // regex to squarePartial
  let squareBaseline = input.includes('squareBaseline=true'); // check to see if squareBaseline

  let transformedOutput = `
  {% set color = "${color}" %}
  {% set heroTitle = "${title}" %}
  {% set subheading = "${subheading}" %}
  {% set background = "${background}" %}
  {% set squarePartial = "${squarePartial.replace('.hbs', '.njk')}" %}
  {% set squareBaseline = ${squareBaseline} %}

  {% include "default-hero.njk" %}`;

  return transformedOutput;
}

const sampleInputTemplate = `{{>
    default-hero
    color="red"
    title="Foo"
    subheading="Bar"
    background="about-us-hero-desktop.jpg"
    squarePartial="company/square.hbs"
    squareBaseline=true
    }}`;

console.log(transformTemplate(sampleInputTemplate));

字符串

7lrncoxx

7lrncoxx2#

我想出来了谢谢大家的帮助。

regex = /\{\{>\s*([a-zA-Z0-9-_/]+)?\s*([a-zA-Z0-9-_/\.=:"'\s]+)\s*\}\}/gi;
var arr = regex.exec(input);
var statements = "";
if (arr && arr[2]) {
  var statementsArray = arr[2].split(/\s+/gi);
  statementsArray = statementsArray.filter(n => n); // filter out falsey values
  statements = statementsArray.map(function (statement) {
    return `{% set ${statement} %}`;
  });
  statements = statements.join("\n");
}
replaceVal = statements + "\n" + '{% include $1.njk %}';
output = input.replace(regex, replaceVal);

字符串

相关问题