Разделение регулярных выражений на массив - PullRequest
2 голосов
/ 16 мая 2019

У меня есть строка элементов в несколько строк (но я могу поменять ее на одну строку, если необходимо), и я хочу разделить ее на элемент

.Я думал, что это будет легко, просто str.split (regex) или даже str.split ('[\ S \ S] 1006 * /;var fndSection = result.split (SecRegex);

Пробовал var fndSection = result.split ('

Ответы [ 3 ]

2 голосов
/ 16 мая 2019

Ваше выражение лица выглядит великолепно!Возможно, вы просто захотите немного изменить его, возможно, что-то похожее на:

/<section[a-z="'\s]+>([\s\S]*?)<\/section>/gmi

RegEx

Если это не ваше желаемое выражение, вы можете изменить / изменить свои выражения в regex101.com .

RegEx Circuit

Вы также можете визуализировать свои выражения в jex.im :

enter image description here

Тест JavaScript

const regex = /<section[a-z="'\s]+>([\s\S]*?)<\/section>/gmi;
const str = `<chapter id="chap1">
<para0><title></title></para0>
</chapter>

<chapter id="chap2"> <title>THEORY</title>
<section id="Thoery">
<title>theory Section</title>
<para0 verstatus="ver">
<title>Theory Para 0 </title>
<text>blah blah</text>
</para0>
</section>

<section id="Next section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<section id="More sections">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<section id="section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Если вы захотите также захватить теги разделов, вы можете просто обернуть все ваше выражение в группу захвата :

const regex = /(<section[a-z="'\s]+>([\s\S]*?)<\/section>)/gmi;
const str = `<chapter id="chap1">
<para0><title></title></para0>
</chapter>

<chapter id="chap2"> <title>THEORY</title>
<section id="Thoery">
<title>theory Section</title>
<para0 verstatus="ver">
<title>Theory Para 0 </title>
<text>blah blah</text>
</para0>
</section>

<section id="Next section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<section id="More sections">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<section id="section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>`;
const subst = `\n$1\n`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: \n', result);
2 голосов
/ 16 мая 2019

Не используйте RegEx для HTML (или любого двоюродного брата HTML). Соберите свой <section>s в NodeList. Преобразуйте этот NodeList в массив. Преобразуйте каждый узел в строку. Это можно сделать в одну строку:

const strings = Array.from(document.querySelectorAll('section')).map(section => section.outerHTML);

Следующая демонстрация является разбивкой примера выше.

// Collect all <section>s into a NodeList
const sections = document.querySelectorAll('section');

// Convert NodeList into an Array
const array = Array.from(sections);

/*
Iterate through Array -- on each <section>...
convert it into a String
*/
const strings = array.map(section => section.outerHTML);

// View array as a template literal for a cleaner look
console.log(`${strings}`);

// Verifying it's an array of mutiple elements
console.log(strings.length);

// Verifying that they are in fact strings
console.log(typeof strings[0]);
<chapter id="chap1">
  <para0>
    <title></title>
  </para0>
</chapter>

<chapter id="chap2">
  <title>THEORY</title>
  <section id="Thoery">
    <title>theory Section</title>
    <para0 verstatus="ver">
      <title>Theory Para 0 </title>
      <text>blah blah</text>
    </para0>
  </section>

  <section id="Next section">
    <title>title</title>
    <para0>
      <title>Title</title>
      <text>blah blah</text>
    </para0>
  </section>

  <section id="More sections">
    <title>title</title>
    <para0>
      <title>Title</title>
      <text>blah blah</text>
    </para0>
  </section>

  <section id="section">
    <title>title</title>
    <para0>
      <title>Title</title>
      <text>blah blah</text>
    </para0>
  </section>

  <chapter id="chap1">
    <para0>
      <title></title>
    </para0>
  </chapter>

  <chapter id="chap1">
    <para0>
      <title></title>
    </para0>
  </chapter>

  <chapter>
    <title>Chapter Title</title>
    <section id="Section ID">
      <title>Section Title</title>
      <para0>
        <title>Para0 Title</title>
        <para>blah blah</para>
      </para0>
    </section>

    <section id="Next section">
      <title>title</title>
      <para0>
        <line>Title</line>
        <text>blah blah</text>
      </para0>
    </section>

    <section id="More sections">
      <title>title</title>
      <para0>
        <list>Title</list>
        <text>blah blah</text>
      </para0>
    </section>

    <section id="section">
      <title>title</title>
      <para0>
        <title>Title</title>
        <text>blah blah</text>
      </para0>
    </section>

    <ipbchap>
      <tags></tags>
    </ipbchap>
1 голос
/ 16 мая 2019

Вам не нужно разбивать строку - вы хотите извлечь данные, которые соответствуют вашему шаблону из нее.Вы можете сделать это, используя String#match.Обратите внимание, что вам нужно добавить флаг g, чтобы получить все совпадения:

var result = `<chapter id="chap1">
<para0><title></title></para0>
</chapter>

<chapter id="chap2"> <title>THEORY</title>
<section id="Thoery">
<title>theory Section</title>
<para0 verstatus="ver">
<title>Theory Para 0 </title>
<text>blah blah</text>
</para0>
</section>

<section id="Next section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<section id="More sections">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<section id="section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<chapter id="chap1">
<para0><title></title></para0>
</chapter>

<chapter id="chap1">
<para0><title></title></para0>
</chapter>

<chapter> <title>Chapter Title</title>
<section id="Section ID">
<title>Section Title</title>
<para0>
<title>Para0 Title</title>
<para>blah blah</para>
</para0>
</section>

<section id="Next section">
<title>title</title>
<para0>
<line>Title</line>
<text>blah blah</text>
</para0>
</section>

<section id="More sections">
<title>title</title>
<para0>
<list>Title</list>
<text>blah blah</text>
</para0>
</section>

<section id="section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<ipbchap>
<tags></tags>
</ipbchap>

</body>
<rear>
<tags></tags>
</rear>
</doc>`;
// the g flag is added ---------------------↓
SecRegex = /<section.*?>[\s\S]*?<\/section>/g;
var fndSection = result.match(SecRegex);


console.log("result string ", fndSection);

Однако вам лучше разбирать DOM и извлекать нужную вам информацию - это просто с помощью DOMParser:

var result = `<chapter id="chap1">
<para0><title></title></para0>
</chapter>

<chapter id="chap2"> <title>THEORY</title>
<section id="Thoery">
<title>theory Section</title>
<para0 verstatus="ver">
<title>Theory Para 0 </title>
<text>blah blah</text>
</para0>
</section>

<section id="Next section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<section id="More sections">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<section id="section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<chapter id="chap1">
<para0><title></title></para0>
</chapter>

<chapter id="chap1">
<para0><title></title></para0>
</chapter>

<chapter> <title>Chapter Title</title>
<section id="Section ID">
<title>Section Title</title>
<para0>
<title>Para0 Title</title>
<para>blah blah</para>
</para0>
</section>

<section id="Next section">
<title>title</title>
<para0>
<line>Title</line>
<text>blah blah</text>
</para0>
</section>

<section id="More sections">
<title>title</title>
<para0>
<list>Title</list>
<text>blah blah</text>
</para0>
</section>

<section id="section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>

<ipbchap>
<tags></tags>
</ipbchap>

</body>
<rear>
<tags></tags>
</rear>
</doc>`

var parser = new DOMParser();
var doc = parser.parseFromString(result, "text/html");

var sections = [...doc.getElementsByTagName("section")];
var fndSection = sections.map(section => section.outerHTML)
console.log(fndSection);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...