How to write a Regular Expression to find a paragraph?

3

What is the correct way to write a Regular Expression to find a paragraph?

// Expressão Regular
var minhaExpressao = /<p>.*</p>/;

How can I fix this variable?

    
asked by anonymous 18.06.2018 / 19:39

3 answers

4

You can use RegExp /^<p>.+<\/p>$/gm , where:

  • ^<p> will ensure that the start of the line is <p>
  • .+ takes all elements after the initial tag, you can change it to better understand this part, for only characters, only numbers, in this case it is for any character
  • <\/p>$ to ensure that the end is </p> remembering to escape the bar
18.06.2018 / 19:51
4

You can use this expression to get the paragraph if it also has line breaks:

<p>[\w\W]+<\/p>

Example:

var p1 = document.querySelector("#div1").textContent;
var p2 = document.querySelector("#div2").textContent;
var re = /<p>[\w\W]+<\/p>/;
var para1 = p1.match(re)[0];
var para2 = p2.match(re)[0];
console.log(para1);
console.log(para2);
<textarea id="div1">
   <p>
      Isto é um parágrafo onde as tags não estão na mesma linha do texto
   </p>
</textarea>

<textarea id="div2">
   <p>Isto é um parágrafo onde as tags estão na mesma linha do texto</p>
</textarea>
\w\W  ->  captura letra e o que não é letra (ou seja, tudo)
+     ->  quantificador que une as ocorrências

See RegExr

    
18.06.2018 / 20:17
2

The only thing that is incorrect in your regex is </p> , the bar should be escaped, thus: /<p>.*<\/p>/ ;

I noticed that no one used a called rearview , that is, you get the reference of a particular group in the order in which it was defined in the expression.

The regex below will catch any type of tag, generalizing a little, but if you want to specify paragraphs just change where has (.*>) and (p>) , this regex will be able to get the opening tag until the tag closing, including the content between tags.

<(.*>).*<\/

Running

let texto = '<p>Este é uma paragrafo</p>

<b>Este é um texto em negrito</b>

<b>Fechamento Incorreto, não deve dar match<b>'

const expressao = /<(.*>).*<\//gm

console.log(texto.match(expressao));

Regex101

    
18.06.2018 / 20:57