0

I want to get specific element nested in few elements with regex and with out using dom parser library and queryselector method.

Regex:

  <art .*?id="src".*?>(?:\s+)?<section .*?class="product".*?>(?:\s+)?<h3>(?:\s+)?(.+?)(?:\s+)?<\/h3><\/section>(?:\s+)?<\/art>

Content:

<art id="src">
  <section class="product">
    <h3>xvd</h3>
    <p>
     sjfdsjvdvds
    </p>
  </section>
  <section class="product">
    <h3>avdsvd</h3>
    <p>
    djsfdsjgdjs
    </p>
  </section>
  <section class="product">
    <h3>zdvdsv</h3>
    <p>
 safdgdsghhrh
    </p>
  </section>
  <section class="product">
    <h3>dd</h3>
    <p>zscsvdsvdsv</p>
  </section>
</art>

Please help me in correcting regex

learner
  • 23
  • 1
  • 6

1 Answers1

0

My guess is that you can likely get those h3 textContents using,

<section .*?class="product".*?>\s*<h3>\s*(.+?)\s*<\/h3>.*?<\/section>\s*

then if you have to check for art element, maybe altering with,

<section .*?class="product".*?>\s*<h3>\s*(.+?)\s*<\/h3>.*?<\/section>\s*|<art .*?id="src".*?>

would be an option, otherwise it'd be pretty complicated with JavaScript.

Demo


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


const regex = /<section .*?class="product".*?>\s*<h3>\s*(.+?)\s*<\/h3>.*?<\/section>\s*|<art .*?id="src".*?>/gs;
const str = `<art id="src">
  <section class="product">
    <h3>xvd</h3>
    <p>
     sjfdsjvdvds
    </p>
  </section>
  <section class="product">
    <h3>avdsvd</h3>
    <p>
    djsfdsjgdjs
    </p>
  </section>
  <section class="product">
    <h3>zdvdsv</h3>
    <p>
 safdgdsghhrh
    </p>
  </section>
  <section class="product">
    <h3>dd</h3>
    <p>zscsvdsvdsv</p>
  </section>
</art>`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
Community
  • 1
  • 1
Emma
  • 27,428
  • 11
  • 44
  • 69
  • could you please help me with the? https://stackoverflow.com/questions/58259069/regex-is-not-matching-data-in-javascript – learner Oct 06 '19 at 16:58