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

0

1 Answer 1

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}`);
    });
}

Sign up to request clarification or add additional context in comments.

1 Comment

could you please help me with the? stackoverflow.com/questions/58259069/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.